繁体   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