首页 > 解决方案 > 开玩笑的模拟调用对象可能是未定义的

问题描述

这是一个使用模拟函数的简单测试。但是我确实收到了模拟调用的 ts 错误Object is possibly 'undefined'.ts(2532)。我不知道如何摆脱这个错误。这是调用对象的结构,所以我认为我正确处理了它......但显然不是ts预期的那样。

import { render, fireEvent } from '@testing-library/react'

const mockSetCheckbox = jest.fn(() => Promise.resolve())

test('should select checkbox', () => {
  // ...
  userEvent.click(checkbox)
  expect(mockSetCheckbox.mock.calls[0][0].variables.input.checkbox).toBe(true)
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   Object is possibly 'undefined'.ts(2532)
})

标签: javascripttypescriptunit-testingjestjs

解决方案


我建议您更改测试以使用.toHaveBeenCalled()

  test("should select checkbox", () => {
    userEvent.click(checkbox)

    expect(mockSetCheckbox).toHaveBeenCalledWith(
      expect.objectContaining({
        variables: expect.objectContaining({
          input: expect.objectContaining({
            checkbox: true,
          }),
        }),
      })
    );
  });

这将断言相同,但是如果实现以不调用函数的方式发生更改,您将得到更容易理解的错误。

使用.toHaveBeenCalled()时会是这样的:

    expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: ObjectContaining {"variables": ObjectContaining {"input": ObjectContaining {"checkbox": true}}}

    Number of calls: 0

工作示例


推荐阅读