簡體   English   中英

使用 Jest 在 React Redux 中對多個分派操作進行單元測試

[英]Unit testing multiple dispatched actions in React Redux with Jest

我有一種感覺,我錯過了一些簡單的東西,但我有一個動作,如果滿足條件,它會分派兩個動作。

行動

export function changeDateRange({ startDate, endDate }) {
  return function reload(dispatch, getState) {
    if (!getState().navigation.focused) {
      // If our datepicker has closed, reload the data on the page
      dispatch(load());
    }
    dispatch({
      type: types.CHANGE_DATE_RANGE,
      startDate,
      endDate
    });
  };
}

然后我試圖測試 load() 並用Jest.fn()它但是當我在調度changeDateRange()后記錄mock.calls.length時它等於0

設置

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
global.mockStore = configureMockStore([thunk]);

測試:

import * as types from '../actionTypes';
import * as changeDateRange from './changeDateRange';
import { load } from '../reporting';

jest.mock('../reporting', () => ({
  load: () => jest.fn()
}));

describe('Reducer: changeDateRange Reducer', () => {
  it('should change date range', () => {
    const store = mockStore({
      startDate: '',
      endDate: '',
      navigation: {
        focused: false
      }
    });
    const dateRange = {
      startDate: 'yes',
      endDate: 'yes'
    };
    store.dispatch(changeDateRange(dateRange));
    expect(store.getActions()).toEqual([
      Object.assign(
        {
          type: types.CHANGE_DATE_RANGE
        },
        dateRange
      )
    ]);
    console.log(load().mock.calls.length); // === 0 ??
  });
});

有任何想法嗎?

奇怪的是,這樣一個老問題沒有答案。 因為它有 8 個贊成票,所以我會為下一個找到它的人回答。 OP 錯誤地模擬了負載。 它應該是這樣的:

jest.mock('../reporting', () => ({
  load: jest.fn() //not () => jest.fn()
}));

然后在代碼中,他們可以這樣做:

console.log(load.mock.calls.length); // not load().mock.calls.length

每次調用 load 時,它都會返回一個新的模擬函數。 實際上load本身需要是模擬函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM