2017-02-16 80 views
0

我一直有问题使用nock来测试我的Redux动作创作者。当我离线时,我不断收到失败的承诺,这意味着使用Axios的HTTP请求不成功。当我上网时,它可以工作,但是。只有在有互联网连接的情况下nock才能工作吗?

那么nock只有在有互联网连接时才能工作?

行动造物主(使用爱可信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 
     }); 
     }); 
    }; 
}; 

玩笑测试行动的创建者(箭扣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'); 
    }); 
}); 

回答

0

似乎有一些问题与使用箭扣测试由爱可信提出了要求。有一个issue in nock's repository讨论。

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

解决方法是删除它。不要使用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 
); 
}); 
0

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

如果您想尝试类似的适配器,无论是在节点,在浏览器的工作原理,看看axios-mock-adapter

+0

我使用axios在我的动作创建者中进行HTTP调用。为了测试,我使用Jest并打电话给nock来设置一个拦截器。看起来拦截器根本没有被使用。当我走出去(或调用nock.disableNetConnect())时,我的axios.get失败并进入其catch块。 – nbkhope

+0

你可以编辑你的问题,让它有你的测试用例吗? –

相关问题