[英]How do I mock and test chained function with jest?
我的組件 useEffect 鈎子中有這個函數鏈。 我將響應/數據設置為我的組件狀態,以便我可以在我的組件中呈現數據。
client
.items()
.type("client")
.toObservable()
.subscribe(response => {
setState(response)
})
我如何模擬這個函數並在組件在我的測試中呈現之前調用它? 我正在使用測試庫/反應。
響應是{items: [{},...]}, somethingElse: {}
您可以使用mockFn.mockReturnThis()來執行此操作。
client.ts
,模擬一個真正的第三方模塊
const client = {
items: () => {
return client;
},
type: (name: string) => {
return client;
},
toObservable: () => {
return client;
},
subscribe: handler => {
handler();
return client;
}
};
export { client };
在 react 組件中使用client.ts
模塊:
class Component {
private props;
constructor(props) {
this.props = props;
}
public componentDidMount() {
this.props.client
.items()
.type('client')
.toObservable()
.subscribe(response => {
this.setState(response);
});
}
private setState(state) {
console.log(state);
}
}
export { Component };
單元測試,真實client.ts
模塊的mock鏈方法,將mocked的client
模塊注入到你的組件中。
import { Component } from './';
const mockClient = {
items: jest.fn().mockReturnThis(),
type: jest.fn().mockReturnThis(),
toObservable: jest.fn().mockReturnThis(),
subscribe: jest.fn().mockReturnThis()
};
const mockProps = {
client: mockClient
};
const component = new Component(mockProps);
describe('Component', () => {
describe('#componentDidMount', () => {
it('should mount the component and set state correctly', () => {
const mockedResponse = { items: [{}], somethingElse: {} };
mockClient.subscribe.mockImplementationOnce(handler => handler(mockedResponse));
// tslint:disable-next-line: no-string-literal
component['setState'] = jest.fn();
component.componentDidMount();
expect(mockClient.items().type).toBeCalledWith('client');
// tslint:disable-next-line: no-string-literal
expect(component['setState']).toBeCalledWith(mockedResponse);
});
});
});
單元測試結果:
PASS src/mock-function/57719741/index.spec.ts
Component
#componentDidMount
✓ should mount the component and set state correctly (6ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.542s, estimated 2s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.