【问题标题】:Does nock only work if there is an Internet connection?nock 是否仅在有 Internet 连接时才有效?
【发布时间】:2017-02-16 23:03:32
【问题描述】:

我在使用 nock 测试我的 Redux 动作创建器时遇到了问题。当我离线时,我不断收到失败的承诺,这意味着使用 Axios 的 HTTP 请求不成功。但是,当我上网时,它可以工作。

那么 nock 是否只有在有 Internet 连接时才有效?

Action Creator(使用 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
        });
      });
  };
};

动作创建者的笑话测试(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');
    });
});

【问题讨论】:

    标签: reactjs testing redux nock


    【解决方案1】:

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

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

    【讨论】:

    • 我使用 axios 在我的动作创建者中进行 HTTP 调用。为了测试,我使用 Jest 并调用 nock 来设置拦截器。似乎根本没有使用拦截器。当我离线(或调用 nock.disableNetConnect())时,我的 axios.get 失败并转到它的 catch 块。
    • 你能编辑你的问题,让它有你的测试用例吗?
    【解决方案2】:

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

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

    解决方案是删除它。不要使用nock.cleanAll()!所以现在一切都可以很好地测试 axios 发出的请求:

    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
      );
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-11
      • 2014-05-22
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多