我正在用React应用程序中的Jest进行单元测试编码,我想检查一个函数是否正确地执行了其(嵌套的)工作。 该函数返回具有三个属性的对象。每个属性都等于一个返回特定函数的匿名函数。我找不到如何测试特定功能及其传递的参数。
这就是整个功能的样子
const myFunction = (param) => {
return {
prop1: (value) => {
return specificFunction(param.someProp1, value);
},
prop2: (value) => {
return specificFunction(param.someProp2, value);
},
prop3: (value) => {
return specificFunction(param.someProp3, value, true);
},
};
};
我要测试
return specificFunction…
行
在阅读JestJS docs之后,我尝试了一种可行的解决方案,但无法控制特定函数的传递参数。
describe('myFunction', () => {
it('should returns object with 3 properties that have an anonymous'
+ 'function that returns a specificFunction with specific parameters'
+ 'passed in', () => {
expect(
myFunction({
someProp1: 'a',
someProp2: 'b',
someProp3: 'c',
}),
).toEqual({
prop1: expect.any(Function),
prop2: expect.any(Function),
prop3: expect.any(Function),
});
});
});
测试通过但没有控制权
我希望我的测试先检查myFunction是否首先调用特定的嵌套函数,并且还使用诸如
的特定参数调用它describe('myFunction', () => {
it("should do the job (I don't want to write the whole (long) description)", () => {
expect(
myFunction({
someProp1: 'a',
someProp2: 'b',
someProp3: 'c',
}),
).toEqual({
prop1: // Check if specificFunction is returned from the anonymous function
//and that the first parameter is 'a' and the second is the parameter from anonymous function
prop2: // Check if specificFunction is returned from the anonymous function
// and that the first parameter is 'b' and the second is the parameter from anonymous function
prop3: // Check if specificFunction is returned from the anonymous function
// and that the first parameter is 'a', the second is the parameter from anonymous function
// and the third parameter is a boolean set to true
});
});
});
我不知道我是否正在尝试以正确的方式解决问题。我愿意接受任何建议,但不能更改初始myFunction的逻辑
答案 0 :(得分:0)
您可能想要类似的东西:
const {prop1, prop2, prop3} = myFunction({
someProp1: 'a',
someProp2: 'b',
someProp3: 'c',
})
expect(prop1(value)).toEqual(
// something here
)
expect(prop2(value)).toEqual(
// something here
)
expect(prop3(value)).toEqual(
// something here
)