我正在尝试在 redux 应用程序中测试 api 调用。该代码几乎遵循中概述的模式异步动作创建者redux 文档的部分:
http://redux.js.org/docs/recipes/WritingTests.html http://redux.js.org/docs/recipes/WritingTests.html
它的要点是你使用redux 模拟商店记录并断言任何触发的操作。
这是整个测试,使用 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'))
});
});
});
但似乎在测试运行时调用了真正的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 分配给变量并将其注销。日志显示:
Nock 似乎将端口 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
有什么想法这里出了什么问题吗?