断言针对抛出的错误对象 [英] asserting against thrown error objects in jest
问题描述
我有一个抛出对象的函数,如何断言正确的对象是在开玩笑?
I have a function which throws an object, how can I assert that the correct object is thrown in jest?
it('should throw', () => {
const errorObj = {
myError: {
name: 'myError',
desc: 'myDescription'
}
};
const fn = () => {
throw errorObj;
}
expect(() => fn()).toThrowError(errorObj);
});
https://repl.it/repls/FrayedViolentBoa
推荐答案
如果您要测试自定义错误的内容(我认为这是您要尝试的操作).您可以捕获该错误,然后执行断言.
If you are looking to test the contents of a custom error (which I think is what you are trying to do). You could catch the error then perform an assertion afterwards.
it('should throw', () => {
let thrownError;
try {
fn();
}
catch(error) {
thrownError = error;
}
expect(thrownError).toEqual(expectedErrorObj);
});
正如Dez所建议的,如果您不抛出javascript Error对象的实例,则toThrowError函数将不起作用.但是,您可以通过装饰错误对象的实例来创建自定义错误.
As Dez has suggested the toThrowError function will not work if you do not throw an instance of a javascript Error object. However, you could create your custom error by decorating an instance of an error object.
例如
let myError = new Error('some message');
myError.data = { name: 'myError',
desc: 'myDescription' };
throw myError;
然后,一旦您在测试中发现错误,就可以测试错误的自定义内容.
Then once you had caught the error in your test you could test the custom contents of the error.
expect(thrownError.data).toEqual({ name: 'myError',
desc: 'myDescription' });
这篇关于断言针对抛出的错误对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!