Redux アプリで API 呼び出しをテストしようとしています。コードは、redux ドキュメントのAsync Action Creatorsセクションで概説されているパターンにほぼ従っています。
http://redux.js.org/docs/recipes/WritingTests.html
その要点は、redux-mock-storeを使用して、トリガーされたアクションを記録およびアサートすることです。
これは、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 から返されます。
これはアクション クリエータ自体です。
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)
}
}
expectedActionsライブの lastFM 応答が、オブジェクトごとに期待している応答と同じではないため、アサーションは失敗します。
nock を変数に割り当ててログアウトしようとしました。ログには次のように表示されます。
Nock は URL にポート 80 を追加しているようですが、これが原因で実際の API がモックされていないかどうかは不明です。
keyedInterceptors: Object{GET http://ws.audioscrobbler.com:80/2.0/?
method=artist.search&artist=john&api_key=abc123&format=json&limit=5
ここで何が問題なのですか?