0

私はreduxテストに不慣れで、アプリケーションのバックフィルテストを試みていましたが、これがnockとredux-mock-storeでテストする完全に間違った方法である場合は申し訳ありません.

//Action in authAction.js
export function fetchMessage() {
  return function(dispatch) {
    axios.get(ROOT_URL, {
      headers: { authorization: localStorage.getItem('token') }
    })
      .then(response => {
        console.log("hi")
        dispatch({
          type: FETCH_MESSAGE,
          payload: response.data.message
        });
      })
      .catch(response => {
        console.log(response)
        //callingRefresh(response,"/feature",dispatch);
      });
  }
}

これはメソッドであり、呼び出されているように見えますが、通常はヘッダーが一致しないというノック失敗の原因をキャッチします。

//authActions_test.js
import nock from 'nock'
import React from 'react'
import {expect} from 'chai'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

import * as actions from '../../src/actions/authActions';
const ROOT_URL = 'http://localhost:3090';

describe('actions', () => {

    beforeEach(() => {
        nock.disableNetConnect();
        localStorage.setItem("token", '12345');
    });

    afterEach(() => {
        nock.cleanAll();
        nock.enableNetConnect();
    });


  describe('feature', () => {

    it('has the correct type', () => {
      var scope = nock(ROOT_URL).get('/',{reqheaders: {'authorization': '12345'}}).reply(200,{ message: 'Super secret code is ABC123' });
      const store = mockStore({ message: '' });

      store.dispatch(actions.fetchMessage()).then(() => {
      const actions = store.getStore()
      expect(actions.message).toEqual('Super secret code is ABC123');
    })


    });
  });
});

ヘッダーが削除され、ノックが通話を傍受した場合でも。毎回このエラーが発生します

TypeError: Cannot read property 'then' of undefined
  at Context.<anonymous> (test/actions/authActions_test.js:43:24)
4

1 に答える 1

1

then呼び出しをチェーンする axios からの約束を返していません。

サンクを次のように変更します。

//Action in authAction.js
export function fetchMessage() {
  return function(dispatch) {
    return axios.get(ROOT_URL, {
      headers: { authorization: localStorage.getItem('token') }
    })
      .then(response => {
        console.log("hi")
        dispatch({
          type: FETCH_MESSAGE,
          payload: response.data.message
        });
      })
      .catch(response => {
        console.log(response)
        //callingRefresh(response,"/feature",dispatch);
      });
  }
}

promise が解決される前に合格しないように、テストを変更する必要がある場合もあります。これを行う方法は、使用するテスト ライブラリによって異なります。モカを使用している場合は、この回答をご覧ください。

補足: アクション クリエーターをリデューサーとは別にテストする他の単体テストがあるかどうかはわかりませんが、これはこれらをテストするための非常に統合された方法です。Redux の大きな利点の 1 つは、マシンの個々のコグを互いに分離して簡単にテストできることです。

于 2017-03-08T05:26:08.833 に答える