0

我试图检查它传递的返回值,但是当我期望toHaveBeenCalledWith相同的函数时它会因no.of 调用失败而失败 is:0。谁能告诉我这段代码有什么问题?

 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
    });
  });

4

1 回答 1

1

price_fromss不是同一个功能,jest.fn() !== jest.fn()。为了通过相等性检查,它应该是相同的:

  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
  });

或者对于无法保留对函数的引用的情况:

  expect(ff).toHaveBeenCalledWith(request as Request, schemaParams, entityName, {
    price_fromss: expect.any(Function)
  });

该断言没有很好的用途,因为它测试的是您刚刚编写的行而不是单元。

于 2020-10-23T07:20:38.020 回答