gpt4 book ai didi

javascript - 针对 Jest 中抛出的错误对象进行断言

转载 作者:行者123 更新时间:2023-12-03 13:33:07 24 4
gpt4 key购买 nike

我有一个抛出对象的函数,我如何断言开 Jest 中抛出了正确的对象?

it('should throw', () => {

const errorObj = {
myError: {
name: 'myError',
desc: 'myDescription'
}
};

const fn = () => {
throw errorObj;
}

expect(() => fn()).toThrowError(errorObj);
});

https://repl.it/repls/FrayedViolentBoa

最佳答案

如果您想测试自定义错误的内容(我认为这就是您想要做的)。您可以捕获错误,然后执行断言。

it('should throw', () => {
let thrownError;

try {
fn();
}
catch(error) {
thrownError = error;
}

expect(thrownError).toEqual(expectedErrorObj);
});

正如 Dez 所建议的,如果您不抛出 javascript Error 对象的实例,toThrowError 函数将不起作用。但是,您可以通过修饰错误对象的实例来创建自定义错误。

例如

let myError = new Error('some message');
myError.data = { name: 'myError',
desc: 'myDescription' };
throw myError;

一旦您在测试中发现错误,您就可以测试错误的自定义内容。

expect(thrownError.data).toEqual({ name: 'myError',
desc: 'myDescription' });

关于javascript - 针对 Jest 中抛出的错误对象进行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com