诺克不拦截我的请求

我正在尝试使用karma服务器和nock来创build一些基本的testing。 看来nock并没有拦截我的请求,有没有人有想法? 我无法弄清楚什么是缺less的。 我仍然获得真实的数据。

nock('https://api.github.com/users/' + username).log(console.log) .get('/') .query(true) .reply(400, { statusMessage: 'Bad Request', foo: 'foo' }) http.get('https://api.github.com/users/' + username, function(res) { console.log('res', res) }) 

我也加了这个中间件

 const middlewares = [thunk]; const mockStore = configureStore(middlewares); 

======更新6月6日======

整个stream程使用react-redux这是我的testing:

 import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import axios from 'axios'; import expect from 'expect'; import * as actions from 'actions/test-actions' import * as types from 'types'; import nock from 'nock' import { username } from 'constansts' const middlewares = [thunk]; const mockStore = configureStore(middlewares); describe('Asynchronous actions', () => { it('Basic example', done => { nock('https://api.github.com') .get('/users/' + username) .reply(400, { statusMessage: 'Bad Request', foo: 'foo' }) var expectedActions = [] let store = mockStore([], expectedActions, done) store.dispatch(actions.testRequest()) .then(() => { console.log('store.getActions() => ', store.getActions()) }) .then(done).catch((err) => { console.log('ERROR==>', err) done() }) }) }) 

这是行动

 export function testRequest () { return axios.get('https://api.github.com/users/' + username) .then(function (res) { console.log('response =>', res.status) }) .catch(function (err) { console.log('error =>', err) }) } 

res.status是200,即使我用nock换成400

您应该在get方法中指定path:

 nock('https://api.github.com').log(console.log) .get('/users/' + username) .query(true) .reply(400, { statusMessage: 'Bad Request', foo: 'foo' }); 

我find了答案!

显然没有与axios兼容,我也尝试了'取','同构取',但没有运气。

“whatwg-fetch”就是答案

非常感谢,我希望这个职位帮助别人。

 import 'whatwg-fetch' export function testRequest () { return fetch('https://api.github.com/users/' + username) .then(function (res) { console.log('response =>', res.status) }) .catch(function (err) { console.log('error =>', err) }) } 

你是在节点环境中还是在Web浏览器(如PhantomJS)中运行testing?

为了使用nock,你必须在节点(使用Jest或者mocha)运行你的testing,nock会覆盖节点的http行为,因此它只能在节点而不是在浏览器(比如PhantomJS)中工作。

要运行testing,您可以:

  • 在节点环境中运行(如Jest或mocha)
  • 或者使用一个不同的库来模拟fetch-mock