我有一张表格。当用户从步骤1转到步骤2时,代码会在将用户移动到步骤2之前检查步骤1中的所有必填字段。当用户在步骤2,3或4时,点击刷新或在新窗口中打开URL ,它们被重定向到介绍页面。
我的问题是测试代码和测试内容。
我正在使用React,Redux,Jest和Sinon。
// actions.js
export const redirectToIntroPage = () => (dispatch, getState) => {
const fields = {
field1: getState().app.inputs.field1,
field2: getState().app.inputs.field2,
field3: getState().app.inputs.field3,
};
if (objHasNullValue(fields)) {
goToPage(PAGES.INTRODUCTION);
}
};
getState()
被多次调用,因为我只关心指定的键。 app
有很多我不需要的东西。
// parsing.js
export const objHasNullValue = obj => {
for (var property in obj) {
if (isNull(obj[property]) === true) {
return true;
}
}
return false;
};
goToPage
是自我解释的。
// action.test.js
describe('redirect to intro page', () => {
let sandbox, fakeDispatch, fakeState, goToPage;
const fakeGetState = () => (fakeState);
beforeEach(() => {
sandbox = sinon.createSandbox();
fakeDispatch = sandbox.stub();
goToPage = sandbox.spy();
});
afterEach(() => {
sandbox.restore();
});
it('should redirect if the Personalisation Form has a null value', () => {
fakeState = {
app: {
inputs: {
field1: null,
field2: null,
field3: null,
},
},
};
redirectToIntroPage()(fakeDispatch, fakeGetState);
expect(goToPage.calledOnce).toBe(true);
});
it('shouldn\'t redirect if the Personalisation Form is complete', () => {
});
});
我对测试的想法是将goToPage
剔除并检查它是否被调用。我必须打电话给redirectToIntroPage()(fakeDispatch, fakeGetState)
这样做,但我如何进入redirectToIntroPage
检查goToPage
已被调用?
我看起来here在概念上有道理,但我如何在Sinon和Jest中翻译它?
我也看了here这是同样的想法。
从参数而不是从外部范围获取goToPage
(因为它很难模拟)。将您的功能拆分为2:
// Use for testing
export const redirectTo = (goToPage) => () => (dispatch, getState) => {
const fields = {
field1: getState().app.inputs.field1,
field2: getState().app.inputs.field2,
field3: getState().app.inputs.field3,
};
if (objHasNullValue(fields)) {
goToPage(PAGES.INTRODUCTION);
}
};
// Use as before
export const redirectToIntroPage = redirectTo(goToPage);