【发布时间】:2020-09-18 14:41:54
【问题描述】:
我有一个函数,它接收一个对象数组并返回一个新的对象数组,简化如下:
const injectArray = (arr, fn) => {
arr.map((el) => ({
...el,
fn: () => fn(el),
}));
};
对此的测试如下所示:
const mockFn = jest.fn();
describe('injectArray()', () => {
it('returns a new array with the function injected into the objects', () => {
expect(injectArray([{
name: 'John Doe',
age: 25
}], mockFn)).toEqual([{
name: 'John Doe',
age: 25,
fn: () => mockFn();
}]);
});
});
测试失败
Expected: [{"name": "John Doe", age: 25, "fn": [Function mockFn]}]
Received: serializes to the same string
当我将测试更改为 toContainEqual() 我得到
Expected value: [{"name": "John Doe", age: 25, "fn": [Function mockFn]}]
Received array: [{"name": "John Doe", age: 25, "fn": [Function mockFn]}]
我相信 Jest 无法比较序列化函数,因此会失败,但在这个特定用例中,我需要将函数传递给对象,如何避免这种情况?
【问题讨论】:
标签: javascript arrays unit-testing oop jestjs