[英]Testing Angular interceptors response with Jest and Spectator
[英]Use jest-mock-extended and Spectator for angular components testing
我已經成功地使用jest-mock-extended來測試服務,它對我來說很好用。 它簡單、易於使用且類型安全。
現在我必須測試 Angular 個組件。 為此,我找到了Spectator 。 我設法使用SpectatorHost
功能為沒有服務的簡單組件編寫測試。 現在我必須用我應該模擬的服務來測試一個組件,但我真的很難做到。
出於這個原因,我想知道是否有一種方法可以將使用jest-mock-extended
創建的模擬注入到使用SpectatorHost
內部生成的組件中。
這樣我也可以使用同一個庫來模擬我項目中的服務。
我找到了如何整合這兩個庫:
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...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.