8

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

ここで何が問題なのですか?

4

3 に答える 3

3

nock を使用するには、ノードで (Jest または mocha を使用して) テストを実行する必要があります。nock はノードの http 動作をオーバーライドするため、ノードでのみ機能し、ブラウザー (PhantomJS など) では機能しません。

たとえば、あなたが指摘したリンクはJestを使用しており、最初の行はノード環境について明示的です。したがって、ノックはチャームとして機能します。 http://redux.js.org/docs/recipes/WritingTests.html

セットアップ

Jest をテスト エンジンとしてお勧めします。これはノード環境で実行されるため、DOM にはアクセスできないことに注意してください。

ご覧のとおり、次のことができます。

于 2016-10-26T19:39:25.877 に答える