Blog>
Snippets

Injection Token with useValue for Testing

Explain how to provide mock values with InjectionTokens in unit tests using the useValue provider.
import { Injector, InjectionToken } from '@angular/core';

// Define an InjectionToken
const MY_CONFIG_TOKEN = new InjectionToken('MyConfig');
This is the definition of an `InjectionToken` which will be used to inject configuration values into a component or service.
// Mock value to be provided in tests
const MY_CONFIG_MOCK = {
  apiUrl: 'https://mock-api.com',
  featureFlag: false
};
Here we are creating a mock configuration object that will be used in our tests to simulate the actual configuration values.
TestBed.configureTestingModule({
  providers: [
    { provide: MY_CONFIG_TOKEN, useValue: MY_CONFIG_MOCK }
  ]
});
This code configures the testing module to use the mock configuration object whenever `MY_CONFIG_TOKEN` is injected. This is done by using the `useValue` provider.
const config = injector.get(MY_CONFIG_TOKEN);
// Now `config` contains { apiUrl: 'https://mock-api.com', featureFlag: false }
Within the test, we can use the `injector` to get the value associated with `MY_CONFIG_TOKEN`, which will be our mock object instead of the real configuration.