我是开玩笑/酶的新手,正尝试模拟对返回Promise的aync函数的调用,该调用是在componentDidMount方法的react组件内进行的。
该测试正在尝试测试componentDidMount将Promise返回的数组设置为状态。
我遇到的问题是,在将数组添加到状态之前,测试已完成并通过。我正在尝试使用“完成”回调来使测试等待,直到承诺解决为止,但这似乎不起作用。
我尝试将Expect调用移至done()调用之前的那一行,但这似乎也不起作用。
谁能告诉我我在做什么错?
正在测试的组件:
componentDidMount() { this.props.adminApi.getItems().then((items) => { this.setState({ items}); }).catch((error) => { this.handleError(error); }); }
我的测试:
import React from 'react'; import { mount } from 'enzyme'; import Create from '../../../src/views/Promotion/Create'; import AdminApiClient from '../../../src/api/'; jest.mock('../../../src/api/AdminApiClient'); describe('view', () => { describe('componentDidMount', () => { test('should load items into state', (done) => { const expectedItems = [{ id: 1 }, { id: 2 }]; AdminApiClient.getItems.mockImplementation(() => { return new Promise((resolve) => { resolve(expectedItems); done(); }); }); const wrapper = mount( <Create adminApi={AdminApiClient} /> ); expect(wrapper.state().items).toBe(expectedItems); }); }); });
您的测试有两个问题。首先,你不能这样嘲笑AdminApiClient。jest.mock将用just替换模块undefined,因此getItems.mockImplementation将无效或抛出错误。同样也不需要使用原始的。通过道具将其作为参数传递时,您可以在测试中直接创建on模拟。其次,如果您使用诺言,则必须从测试中返回诺言或使用async/await(docs):
AdminApiClient
jest.mock
undefined
getItems.mockImplementation
async/await
it('', async() = > { const expectedItems = [{ id: 1 }, { id: 2 }]; const p = Promise.resolve(expectedItems) AdminApiClient = { getItems: () = > p } const wrapper = mount( <Create adminApi={AdminApiClient} /> ); await p expect(wrapper.state().items).toBe(expectedItems); })