I'm already using successfully using jest-mock-extended to test services and it works fine for me. It's simple, easy to use and type safe.
Now I have to test Angular components. For this purpose I've found Spectator. I managed to write tests for simple components without services using the SpectatorHost
feature. Now I've to test a component with a service that I should mock but I'm really finding hard time to do it.
For this reason I was wondering if there's a way to inject the mock created with jest-mock-extended
into the component generated inside with SpectatorHost
.
In this way I would also use the same library to mock the services in my project.
I found how to integrate the two libraries:
describe('MyComponent', () => {
// SpectatorHost object and factory
let host: SpectatorHost<MyComponent>;
const createHost = createHostFactory({
component: MyComponent,
mocks: [MyService], // Automatically mock service used by the component
});
// MockProxy object from jest-mock-extended
let myServiceMock: MockProxy<MyService>;
// Init and reset service before each test
beforeEach(() => {
myServiceMock = mock<MyService>();
mockReset(MyService);
});
it('...', () => {
// Mock whatever function in the service
myServiceMock.doSomething.mockReturnValue('Mock');
host = createHost('<my-component></my-component>', {
providers: [{ provide: MyService, useValue: myServiceMock }] // Pass mocked service to the component
});
// Rest of the test...
});