我有一个看起来像这样的组件
async componentDidMount() {
const { navigation } = this.props
this.subs = [
navigation.addListener('didFocus', () => this.onComponentFocus()),
]
}
onComponentFocus() {
const { dispatch } = this.props
dispatch(fetchDevices())
}
现在,我想编写一个测试一次,以便让chekcs fetchDevice被调用。第一个想法是像这样模拟导航
常量导航= { 导航:jest.fn(), }
但是现在如何检查this.subs以及如何检查fetchDevices被解雇了?
答案 0 :(得分:1)
如果我们假设fetchDevices
来自图书馆
Component.spec.js
import fetchDevices from 'device-fetcher';
jest.mock('device-fetcher');
// as your component accepts the dispatch function
// you can create it as mock function
const mockDispatch = jest.fn();
// since in your implementation you're calling navigation.addListener
const mockNavigation = {
navigate: jest.fn(),
// it should also have
addListener: jest.fn()
};
describe('Component', () => {
const wrapper = shallow(<Component navigation={mockNavigation} dispatch={mockDispatch} />);
describe('navigation didFocus', () => {
beforeAll(() => {
// get .addEventListener calls with 'didFocus'
mockNavigation.addEventListener.mock.calls
.filter(([eventName]) => eventName === 'didFocus')
// iterate over the "attached" handlers
.map(([eventName, eventHandler]) => {
// and trigger them
eventHandler();
});
});
it('should have called the dispatch with the result of fetchDevices', () => {
expect(mockDispatch).toHaveBeenCalledWith(
fetchDevices.mock.results[0].value
);
});
});
});
注意:未经测试,只是解决方案概述
编辑:如果fetchDevices
是属性,而不是模拟库,则您定义模拟函数
const fetchDevices = jest.fn();
// and pass it to the component
shallow(<Component navigation={mockNavigation} dispatch={mockDispatch} fetchDevices={fetchDevices} />);
然后您应该具有相同的断言