在Reduxtesting中,Nock不拦截API调用

我试图在一个REDX应用程序中testing一个API调用。 该代码非常符合redux文档的Async Action Creators部分中概述的模式:

http://redux.js.org/docs/recipes/WritingTests.html

它的要点是,你使用减less模拟商店logging和断言任何触发的行动。

这是整个testing,用nock来模拟api调用:

import React from 'React' import ReactDOM from 'react-dom' import expect from 'expect'; import expectJSX from 'expect-jsx'; import TestUtils from 'react-addons-test-utils' import configureMockStore from 'redux-mock-store' import thunk from 'redux-thunk' import nock from 'nock' expect.extend(expectJSX); import * as types from '../../constants/Actions' describe('Async Search Actions', () => { const thunkMiddleware = [ thunk ]; /* use redux-mock-store here */ const mockStore = configureMockStore(thunkMiddleware); describe('The fetchArtistData action creator should', () => { afterEach(() => { nock.cleanAll() }) it('Should fire off a ARTIST action when fetch is done', (done) => { nock('http://ws.audioscrobbler.com') .get('/2.0/') .query({method: 'artist.search', artist: 'ho', api_key: 'abc123', format: 'json', limit: 5}) .reply(200, { fake: true } ) const expectedActions = [ { type: types.ARTIST, artists: { fake: true } } ]; let store = mockStore([], expectedActions, done); store.dispatch(fetchArtist('ho')) }); }); }); 

但是,似乎在testing运行时调用真正的lastFm api …真正的数据是从lastFm而不是假nock响应返回的。

这是动作创造者本身:

 export function fetchArtist(search) { return dispatch => { return fetch(`http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=${search}&api_key=abc123&format=json&limit=5`) .then(handleErrors) .then(response => response.json()) .then(json => { dispatch(ArtistData(searchTerm, json)) }) .catch(handleServerErrors) } } 

断言失败,因为活的lastFM响应是不同于我预期的响应相同的expectedActions对象..

我已经尝试将nock分配给一个variables并将其注销。日志显示了这一点:

诺克似乎是join到端口80的URL,不知道这是否导致实际的API不被模拟:

  keyedInterceptors: Object{GET http://ws.audioscrobbler.com:80/2.0/? method=artist.search&artist=john&api_key=abc123&format=json&limit=5 

任何想法这里有什么不对?

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

例如,您指出的链接是使用Jest,并且第一行显示了节点环境。 所以,诺克将作为一种魅力。 http://redux.js.org/docs/recipes/WritingTests.html

configuration

我们推荐Jest作为testing引擎。 请注意,它在Node环境中运行,所以您将无法访问DOM。

正如我所见,你可以:

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

您只需将基本URL传递给主要的nock函数,并将URLpath部分分离到.get()方法中。

 nock('http://ws.audioscrobbler.com') .get('/2.0/') .query({ method: 'artist.search', artist: 'bob', api_key: 'somekey123', format: 'json', limit: '5' }) .reply(200, {fake: true}) 

上面的代码我能够得到一个假的回应。