如何使用相同的功能检查`toHaveBeenCalledWith` [英] How to check `toHaveBeenCalledWith` with same function
问题描述
我试图检查传递的返回值,但是当我期望toHaveBeenCalledWith
相同的函数时,它会失败,并出现 no.of.call::0 .谁能告诉我这段代码有什么问题吗?
I was trying to check the return value its passed but when i expect toHaveBeenCalledWith
same function it gets failed with no.of calls is:0. Can anyone tell me whats wrong in this code?
describe('buildAggregateParams', () => {
// Preparing
const schemaParams = {
filterKeyMap: {
id: '_id',
name: 'test_name',
no: '_no',
},
sortKeyMap: {
date: '_created_date',
no: '_no',
name: 'test_name',
status: '_status_is_active',
},
lookups: [
{
from: 'sample',
localField: 'test_id',
foreignField: '_id',
as: 'test_id',
model: 'sampleModel',
},
],
unwinds: [],
queryKeys: ['page', 'size', 'sort', 'order_by', 'from', 'to', 'status'],
};
const entityName = 'test_collection';
it('test 1.', async () => {
// Preparing
const request = ({
query: {
price_fromss: '2',
},
originalUrl: '/api/m3/product/all/?price_fromss=2',
} as unknown) as Request;
const expectBuildAggregateParamsResult = {
filters: { test_collection_status_is_active: true },
pageSort: { limit: 25, skip: 0, sort: {} },
filterKeyMap: { id: '_id', name: 'test_name', no: '_no' },
sortKeyMap: {
date: '_created_date',
no: '_no',
name: 'test_name',
status: '_status_is_active',
},
lookups: [
{
from: 'sample',
localField: 'test_id',
foreignField: '_id',
as: 'test_id',
model: 'sampleModel',
},
],
unwinds: [],
queryKeys: ['page', 'size', 'sort', 'order_by', 'from', 'to', 'status'],
};
const ff = jest.spyOn(ControllerUtility, 'buildAggregateParams');
// Executings
const result = await buildAggregateParams(request as Request, schemaParams, entityName, {
price_fromss: jest.fn(),
});
expect(result).toEqual(expectBuildAggregateParamsResult); // Passed
expect(ff).toHaveBeenCalledWith(request as Request, schemaParams, entityName, {
price_fromss: jest.fn(),
}); //Failed
});
});
推荐答案
price_fromss
是同一个函数,jest.fn() !== jest.fn()
.为了通过相等性检查,它应该是相同的:
price_fromss
is not the same function, jest.fn() !== jest.fn()
. In order to pass the equality check it should be the same:
const price_fromss = jest.fn();
const result = await buildAggregateParams(request as Request, schemaParams, entityName, {
price_fromss
});
expect(ff).toHaveBeenCalledWith(request as Request, schemaParams, entityName, {
price_fromss
});
或者在无法保留对函数的引用的情况下:
Or for a case when it's impossible to keep a reference to a function:
expect(ff).toHaveBeenCalledWith(request as Request, schemaParams, entityName, {
price_fromss: expect.any(Function)
});
断言的用处不大,因为它会测试您刚刚编写的行而不是单元.
The assertion doesn't serve a good purpose because it tests the line you've just written and not the unit.
这篇关于如何使用相同的功能检查`toHaveBeenCalledWith`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!