测试Redux函数

问题描述

我正在测试这样的功能

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

为此,我使用玩笑编写了一个模拟测试

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