javascript - 开玩笑的模拟调用对象可能是未定义的
问题描述
这是一个使用模拟函数的简单测试。但是我确实收到了模拟调用的 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)
})
解决方案
我建议您更改测试以使用.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
推荐阅读
- node.js - 为什么猫鼬 findOne 返回 null
- android - java.lang.ClassCastException: androidx.preference.PreferenceScreen 不能转换为 android.preference.GenericInflater$Parent
- c# - 使用 unity3D 实用程序反序列化包含嵌套对象的 Json 字符串
- html - Flutter Web Iframe html元素错误重新加载
- flutter - 使用 assets_audio_player 颤振音频滑块
- reactjs - 使用 React 进行照片上传验证
- javascript - JQuery在文本末尾单击时删除完整链接
- c++ - 修改 value const 方法
- mongodb - Mongodb - 如果元素不在数据库中,如何使用 $inc
- google-apps-script - 更新 A 列中的单元格时创建新工作表