簡體   English   中英

測試 redux function

[英]Testing a redux function

我正在測試這樣的 function

export default (middlewares) => {
    return createStore(rootReducer, applyMiddleware(...middlewares));
};

為此,我使用 jest 編寫了一個模擬測試

import { createStore } from 'redux';
import createGlobalStore from '../store';

jest.mock('redux');

describe('Store test', () => {
    it('testing create global store', () => {
        const mockTestValue = 1;
        createStore.mockResolvedValue(mockTestValue);
        expect(createGlobalStore([])).toBe(mockTestValue);
    });
});

但是我的代碼失敗了。

expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: {}

我不確定我是否編寫了正確的測試用例。 任何人都可以幫助我糾正這個或更好地編寫這個測試用例嗎?

您正在編寫單元測試。 下面是比較完整的單元測試代碼。

index.ts

import { createStore, applyMiddleware } from 'redux';

function rootReducer(state) {
  return state;
}

export default (middlewares) => {
  return createStore(rootReducer, applyMiddleware(...middlewares));
};

index.test.js

import createGlobalStore from './';
import { createStore, applyMiddleware } from 'redux';

jest.mock('redux');

describe('63369776', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', () => {
    const mockTestValue = 1;
    createStore.mockReturnValueOnce(mockTestValue);
    applyMiddleware.mockReturnValueOnce('store enhancer');
    expect(createGlobalStore([])).toBe(mockTestValue);
    expect(createStore).toBeCalledWith(expect.any(Function), 'store enhancer');
    expect(applyMiddleware).toBeCalledWith(...[]);
  });
});

帶有覆蓋率報告的單元測試結果:

 PASS  src/stackoverflow/63369776/index.test.js (11.603s)
  63369776
    ✓ should pass (7ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |       75 |      100 |       50 |       75 |                   |
 index.js |       75 |      100 |       50 |       75 |                 4 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.977s

源代碼: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63369776

暫無
暫無

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

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