如何使用Moxios和Jest测试诺言的回报

时间:2019-10-04 14:14:33

标签: promise jestjs moxios

我正试图了解如何使Moxios发挥应有的作用。 我正在测试此功能:

const test_mock_req = () => {
  return API.get('/internal/timeo/api/v0/actions').then(response => response);
};

这是我尝试使用jest和moxios进行设置的测试。当我使用await/async时,它会起作用:

it('test_mock_req', async () => {
  moxios.stubRequest('/internal/timeo/api/v0/actions', {
    status: 200,
    response: 'A mocked response'
  });
  const result = await test_mock_req();
  expect(result.data).toEqual('A mocked response');
});

但是,当我尝试在没有async/await的情况下进行测试但使用.then时却无效:


it('test_mock_req without await/async', () => {
  moxios.stubRequest('/internal/timeo/api/v0/actions', {
    status: 200,
    response: 'A mocked response'
  });

  const result = test_mock_req();

  result.then(resp => {
    console.log(resp);
    console.log('why dont you print');
    expect(resp.data).toEqual('A mocked response');
  });
});

我从不设法console.log(resp)console.log("why dont you print") 这是为什么 ?我在这里想念什么?我也尝试过将stubRequest包裹在moxios.wait中,但是效果不佳:

   moxios.wait(() => {
      const request = moxios.requests.mostRecent()
      request.respondWith({
        status: 200,
        response: "A mocked response"
      });
    })

0 个答案:

没有答案