我在使用React进行Jest测试时遇到了一个问题。我也在使用酶。此外,我正在使用Redux。
如果您看到下面的jest测试,您将看到两个模拟的点击。在下面的测试中出现两次模拟点击的原因是"showAddItem“检查中的输入都是隐藏的。单击"div#add_item“允许该div可见。在此之后,单击"input#add_item_submit“应该会调用addItemToWatchList。
在我使用调试器进行测试并运行测试时,第一次模拟单击确实会将状态设置为showAddItem为true。这允许输入"add_item_submit“在DOM中可用。之后,测试中的第二次模拟单击似乎不会触发,因为没有调用addItemToWatchList。我的测试输出是:
Expected number of calls: >= 1
Received number of calls: 0
相关react组件代码:
{ this.state.showAddItem ? <div>
<input type="text" name="watchListItem" value={this.state.watchListItem}
onChange={this.handleInputChange}></input><br />
<input type="submit" id="add_item_submit" value="Add Item"
onClick={ () => this.addItemToWatchList()}/>
</div> : null }
相关Jest/酶测试
it('should call addItemToWatchList when adding a item', () => {
const initialState = { userReducer: {user: { id: 1, email: "test@test.com"}} }
const mockStore = configureStore([]);
const store = mockStore(initialState);
const component = mount(<Provider store={store}>
<AddItem />
</Provider>);
const mockedAddItemToWatchList = jest.fn();
component.instance().addItemToWatchList = mockedAddItemToWatchList
//sets state to showAddItem to true
component.find('div#add_item').simulate('click')
component.find('input#add_item_submit').simulate('click')
expect(mockedAddItemToWatchList).toHaveBeenCalled()
});
顺便说一句,我也尝试过做jest.spyOn,但也没有任何运气。
发布于 2020-03-23 01:42:12
component.instance()可能返回所提供的实例。你可以尝试直接挂载AddItem,模拟它的内部方法行为。
const component = mount(
<AddItem />);
https://stackoverflow.com/questions/60801845
复制相似问题