Javascript jest模拟调用对象可能未定义
这是一个简单的测试。但是我确实收到了一个ts错误,因为模拟调用Javascript jest模拟调用对象可能未定义,javascript,typescript,unit-testing,jestjs,Javascript,Typescript,Unit Testing,Jestjs,这是一个简单的测试。但是我确实收到了一个ts错误,因为模拟调用对象可能是“未定义的”。ts(2532)。我不知道如何消除这个错误。调用对象,所以我认为我正确地处理了它。。。但显然不像ts预期的那样 import { render, fireEvent } from '@testing-library/react' const mockSetCheckbox = jest.fn(() => Promise.resolve()) test('should select checkbox',
对象可能是“未定义的”。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)
})
这意味着
mockSetCheckbox.mock.calls[0][0]
可能是未定义的
,因为您可能正在执行mockSetCheckbox.mock.undefined.variables
,并且您不能像这样引用未定义的
它试图帮助您,因为您的调用[0][0]
的类型是未定义的
和/或其他类型
最简单的修复方法是先检查,确保检查程序不会未定义。如果您不想要一个bunchaif
s,可以使用快捷方式更简洁地执行此操作
if(mockSetCheckbox.mock.calls[0][0]) {
expect(mockSetCheckbox.mock.calls[0][0].variables.input.checkbox).toBe(true)
}
如果抛出未定义,您可能还希望确保测试失败。上述操作将自动失败,因为noexpect
s表示“通过”。我更喜欢通过发现问题和寻找问题后假设一切都很好来做到这两个方面
比如:
if(mockSetCheckbox.mock.calls[0][0] === undefined) {
throw "oh no!";
}
expect(mockSetCheckbox.mock.calls[0][0].variables.input.checkbox).toBe(true)
其他选择包括:
expect(mockSetCheckbox.mock.!calls[0][0].variables.checkbox).toBe(true);
// or
expect((mockSetCheckbox.mock.calls[0][0] as Something).variables.input.checkbox).toBe(true);
// or
let val:Something = mockSetCheckbox.mock.calls[0][0];
expect(val.variables.input.checkbox).toBe(true);
。。。其中Something
是包含variables
对象(或any
)的任何类型。我建议您将测试更改为使用
这将断言相同,但如果实现以不调用函数的方式更改,则会得到更容易理解的错误
使用.tohavebeencall()时,
将如下所示:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: ObjectContaining {"variables": ObjectContaining {"input": ObjectContaining {"checkbox": true}}}
Number of calls: 0
如果我执行let val=mockSetCheckbox.mock.calls[0][0]
,我确实会得到长度为“0”的元组类型“[]”在索引“0”处没有元素。最后一个括号是ts(2493)
。因为这是一个测试用例,我认为非空断言代码>最佳传达意图。不过,您的示例并不完全正确,它应该在第二次数组访问之后出现:mockSetCheckbox.mock.calls[0][0]!。变量。复选框
不可更改代码>不会改变任何东西。我可以执行mock.calls[0]?[0]
,但这给了我属性“variables”在类型“number[]”上不存在的机会。
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: ObjectContaining {"variables": ObjectContaining {"input": ObjectContaining {"checkbox": true}}}
Number of calls: 0