如果有Internet连接,nock是否只能工作?

时间:2017-02-16 23:03:33

标签: reactjs testing redux nock

我一直在使用 nock 来测试我的Redux动作创建者。当我离线时,我一直收到失败的承诺,这意味着使用Axios的HTTP请求没有成功。当我上网时,它可以工作。

  

如果有互联网连接,那么nock只能工作吗?

行动创作者(使用axios 0.15.3)

export const fetchSomething = (id) => {
  return dispatch => {
    dispatch({
      type: FETCH_SOMETHING_LOADING
    });

    return axios.get(`${SOMEWHERE}/something?id=${id}`)
      .then(response => {
        return dispatch({
          type: FETCH_SOMETHING_SUCCESS,
          payload: response.data
        });
      })
      .catch(error => {
        return dispatch({
          type: FETCH_SOMETHING_FAILURE
        });
      });
  };
};

动作创建者的Jest测试(nock v9.0.2)

test('should dispatch success action type if data is fetched successfully', () => {
  // Need this in order for axios to work with nock
  axios.defaults.adapter = require('axios/lib/adapters/http');

  nock(SOMEWHERE)
    .get('/something?id=123')
    .reply(200, someFakeObject);

  thunk = fetchSomething(123);

  return thunk(dispatch)
    .then(() => {
      expect(dispatch.mock.calls[1][0].type).toBe('FETCH_SOMETHING_SUCCESS');
    });
});

2 个答案:

答案 0 :(得分:0)

据我所知,nock npm模块仅适用于Node,而不适用于浏览器。您是在测试套件中使用nock,还是在开发时作为API的填充?如果是后者,我不认为nock中间件会起作用。当你连接到互联网时,你可能会看到来自真实API而不是模拟api的响应,并且nock不会拦截任何东西。

如果您想尝试在节点和浏览器中都能运行的类似适配器,请查看axios-mock-adapter

答案 1 :(得分:0)

使用nock测试axios发出的请求似乎存在一些问题。有一个issue in nock's repository讨论了这一点。

我发现@supnate对该问题的评论解决了我的问题。此外,我在我的代码中调用了nock.cleanAll();内部beforeEach()内部nock.cleanAll()这个问题的罪魁祸首

解决方案是删除它。不要使用import axios from 'axios'; import httpAdapter from 'axios/lib/adapters/http'; axios.defaults.host = SOMEWHERE; // e.g. http://www.somewhere.com axios.defaults.adapter = httpAdapter; describe('Your Test', () => { test('should do something', () => { nock(SOMEWHERE) .get('/some/thing/3') .reply(200, { some: 'thing', bla: 123 }); // then test your stuff here ); }); !所以现在一切都能很好地测试axios发出的请求:

<% include templates/header %>
<h1> Index page!</h1>
<% include templates/footer %>