我正在尝试使用proxyquire
单元测试我的 Redux 减速器。我需要在我的测试中替换一个函数的功能,但保留另一个函数的原始功能,根据proxyquire's
文档这是可能的。
formsReducer.test.js:
import { expect } from 'chai';
import * as types from '../constants/actionTypes';
import testData from '../data/TestData';
import proxyquire from 'proxyquire';
describe('Forms Reducer', () => {
describe('types.UPDATE_PRODUCT', () => {
it('should get new form blueprints when the product changes', () => {
//arrange
const initialState = {
blueprints: [ testData.ipsBlueprint ],
instances: [ testData.basicFormInstance ]
};
//use proxyquire to stub call to formsHelper.getFormsByProductId
const formsReducerProxy = proxyquire.noCallThru().load('./formsReducer', {
'../utils/FormsHelper': {
getFormsByProductId: () => { return initialState.blueprints; }
}
}).default;
const action = {
type: types.UPDATE_PRODUCT,
stateOfResidence: testData.alabamaObject,
product: testData.basicProduct
};
//act
const newState = formsReducerProxy(initialState, action);
//assert
expect(newState.blueprints).to.be.an('array');
expect(newState.blueprints).to.equal(initialState.blueprints);
});
});
});
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.getFormsByProductId()
但保留的原始功能formsHelper.addOrRemoveMnDisclosure()
- 正如您在proxyquire
块中看到的那样,我只是替换getFormsByProductId()
功能。但是,当我这样做时,会出现以下错误:TypeError: _FormsHelper2.default.addOrRemoveMnDisclosure is not a function
. 看起来是 babel 或我export default
的 for FormHelper 的问题。
FormsHelper 的导出如下所示:
export default class FormsHelper { ...methods and whatnot }
.
我该如何解决这个问题?