angular-testing-library
angular-testing-library copied to clipboard
Add getInstanceWithProviders() utility for testing services with dependencies
I am currently introducing testing-library for angular with vitest at our company and learned that while there is the very handy render() function in testing-library, an alternative for testing services or facades with injections did not exist.
I added a small new function getInstanceWithProviders() to the library which simplifies dependency injections into services or facades.
Example
@Injectable()
class DatabaseService {
getData() {
return 'real data';
}
}
@Injectable()
class UserService {
private db = inject(DatabaseService);
getUser() {
return `User: ${this.db.getData()}`;
}
}
// Test with mocked dependency
it('should inject a mock service into a service that depends on it', () => {
const mockDatabase = { getData: () => 'mock data' };
const userService = getInstanceWithProviders(UserService, [
{ provide: DatabaseService, useValue: mockDatabase }
]);
expect(userService.getUser()).toBe('User: mock data');
});
I have already created a test file for the new function and can also provide an example in the example project if this addition to the library is desired.