模块中的模拟异步功能

时间:2018-03-25 11:22:09

标签: reactjs jestjs enzyme

如何使用throw错误模拟api返回?

it('should display error if request fails', async () => {
  const preventDefault = jest.fn();
  const urlCalled = `${apiHost}/json/aaac.co`;
  const wrapper = mount(<WebsiteLocationSearch />);
  wrapper.find('#host').instance().value = 'aaac.co';
  wrapper.simulate('submit', { preventDefault });

  // getHostLocation should return an promise with error.. how? I tried...
  api.getHostLocation.mockResolvedValue(() => {});

  await fetchMock.flush();
  wrapper.update();
  const errorFields = wrapper.find('.error');
  return expect(errorFields).toHaveLength(1);
});

在我的组件上..

import getHostLocation from 'api';

...

async onSubmit(e) {
  e.preventDefault();
  try {
    this.setState(setLoading(true));
    const host = this.$form.form('get value', 'host');
    await getHostLocation(host); // how to mock this and throw error?
  } catch (error) {
    this.$form.form('add prompt', 'host', error.message);
  } finally {
    this.setState(setLoading(false));
  }
}

api模块只是帮助使用api

// api module
export default function getHostLocation(host) {
  return fetch(`${apiHost}/json/${host}`)
}

0 个答案:

没有答案