用Jest测试功能中的功能?

时间:2019-05-01 13:10:21

标签: jestjs

我正在用Jest测试Redux Action Creator

这是动作创建者:

const addDiscount = ({ code }) => (dispatch, getState) => {
    const { id } = getState().token;

    return dispatch({
        apiCall: discount.put({
            body: {
                code
            },
            id,
        }),
        types: ADD_DISCOUNT.triplet,
    });
};

这是我的考验:

const apiCallMock = jest.fn()
const dispatch = jest.fn(() => {
    return {
        apiCall: apiCallMock,
    };
});
const customerOrderId = 'customer-order-id';
const getState = jest.fn(() => ({
    token: {
        customerOrderId,
    },
}));

const res = addDiscount({ code: 'abc123' })(dispatch, getState);

console.log(res)
console.log(dispatch.mock.calls[0][0]);
console.log(apiCallMock.mock);

如果我尝试console.log(res),则结果不确定。

console.log(dispatch.mock.calls[0][0]);显示了我的类型,但apiCall是尚未运行的函数。

console.log(apiCallMock.mock);似乎尚未运行

1 个答案:

答案 0 :(得分:0)

这里是仅使用jest的单元测试解决方案:

index.ts

import { discount } from './discount';

export const ADD_DISCOUNT = {
  triplet: 'triplet'
};

export const addDiscount = ({ code }) => (dispatch, getState) => {
  const { id } = getState().token;

  return dispatch({
    apiCall: discount.put({ body: { code }, id }),
    types: ADD_DISCOUNT.triplet
  });
};

discount.ts

export const discount = {
  put(obj) {
    return obj;
  }
};

index.spec.ts

import { addDiscount, ADD_DISCOUNT } from './';
import { discount } from './discount';

describe('addDiscount', () => {
  test('should ', () => {
    const customerOrderId = 'customer-order-id';
    const mDispatch = jest.fn();
    const mGetState = jest.fn().mockReturnValueOnce({ token: { id: customerOrderId } });
    const putSpy = jest.spyOn(discount, 'put');
    addDiscount({ code: 'abc123' })(mDispatch, mGetState);
    expect(mGetState).toBeCalledTimes(1);
    expect(mDispatch).toBeCalledWith({
      apiCall: { body: { code: 'abc123' }, id: customerOrderId },
      types: ADD_DISCOUNT.triplet
    });
    expect(putSpy).toBeCalledWith({ body: { code: 'abc123' }, id: customerOrderId });
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/55936794/index.spec.ts (9.651s)
  addDiscount
    ✓ should dispatch action correctly (7ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |      100 |      100 |      100 |      100 |                   |
 discount.ts |      100 |      100 |      100 |      100 |                   |
 index.ts    |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.79s

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