如何对依赖于另一个的方法进行单元测试?

时间:2016-09-19 15:40:02

标签: javascript unit-testing redux

我有一个React和Redux项目,我试图用Chai测试框架进行单元测试。现在我正在为我的减速器编写一个测试,并且这个减速器处理的几个动作调用了辅助方法。这是一个例子:

formsReducer.js:

import * as types from '../constants/actionTypes';
import objectAssign from 'object-assign';
import initialState from './initialState';
import formsHelper from '../utils/FormsHelper';
export default function formsReducer(state = initialState.forms, action) {
  switch (action.type) {
    case types.UPDATE_PRODUCT: {
        let formBlueprints = formsHelper.getFormsByProductId(action.product.id);
        formBlueprints = formsHelper.addOrRemoveMnDisclosure(formBlueprints, action.stateOfResidence.id);
        return objectAssign({}, state, {blueprints: formBlueprints, instances: []});
    }
  }
}

正如您所看到的,如果我测试此方法,我依赖于formsHelper.getFormsByProductIdformsHelper.addOrRemoveMnDisclosure方法也可以通过。我该如何测试这种减速器/动作?当某个product.id传递给这些方法时,我是否应该创建一组可以从这些方法返回的单独的测试数据?

1 个答案:

答案 0 :(得分:0)

这里有几个选项:您可以使用nock拦截请求(如果它进行http调用)或使用proxyquire模拟依赖项。假设您将mochachai结合使用,以下是一些可以帮助您入门的示例。

nock示例

const nock = require('nock');

describe('your test', () => {
  if('should do things', () => {
    nock('http://your-domain')
      .get('/forms/1') // <---- or any other resource
      .reply(200, { /* your response object for testing */ });

    /* Your regular test */
  });
});

proxyquire示例

const proxyquire = require('proxyquire');

describe('your test', () => {
  if('should do things', () => {
    const formsReducer = proxyquire.noCallThru().load('../reducers/forms', {
      formsHelper: {
        /* any keys you need mocked/replaced for your test */
        getFormsByProductId: id => return { /* mock response */ }
      }
    });

    /* Your regular test */
  });
});