我有一个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.getFormsByProductId
和formsHelper.addOrRemoveMnDisclosure
方法也可以通过。我该如何测试这种减速器/动作?当某个product.id传递给这些方法时,我是否应该创建一组可以从这些方法返回的单独的测试数据?
答案 0 :(得分:0)
这里有几个选项:您可以使用nock
拦截请求(如果它进行http调用)或使用proxyquire
模拟依赖项。假设您将mocha
与chai
结合使用,以下是一些可以帮助您入门的示例。
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 */
});
});