Dan*_*ham 2 javascript reactjs jestjs
我有一个抛出对象的函数,如何断言正确的对象是在开玩笑呢?
it('should throw', () => {
const errorObj = {
myError: {
name: 'myError',
desc: 'myDescription'
}
};
const fn = () => {
throw errorObj;
}
expect(() => fn()).toThrowError(errorObj);
});
Run Code Online (Sandbox Code Playgroud)
Dun*_*der 11
如果您要测试自定义错误的内容(我认为这是您要尝试的操作)。您可以捕获错误,然后执行断言。
it('should throw', () => {
let thrownError;
try {
fn();
}
catch(error) {
thrownError = error;
}
expect(thrownError).toEqual(expectedErrorObj);
});
Run Code Online (Sandbox Code Playgroud)
正如Dez所建议的,如果您不抛出javascript Error对象的实例,则toThrowError函数将不起作用。但是,您可以通过装饰错误对象的实例来创建自定义错误。
例如
let myError = new Error('some message');
myError.data = { name: 'myError',
desc: 'myDescription' };
throw myError;
Run Code Online (Sandbox Code Playgroud)
然后,一旦在测试中发现错误,就可以测试错误的自定义内容。
expect(thrownError.data).toEqual({ name: 'myError',
desc: 'myDescription' });
Run Code Online (Sandbox Code Playgroud)
You need to throw a Javascript Error object, so the Jest toThrowError method identifies that an error has been thrown. Also the toThrowError looks to match the message of the error thrown or if an error has been thrown if you just check by .toThrowError().
it('should throw', () => {
const errorObj = {
myError: {
name: 'myError',
desc: 'myDescription'
}
};
const fn = () => {
throw new Error(errorObj.myError.desc);
}
expect(() => fn()).toThrowError("myDescription");
});
Run Code Online (Sandbox Code Playgroud)
If you want to check the whole object is being passed as it is, you need to check it like this:
it('should throw', () => {
const errorObj = {
myError: {
name: 'myError',
desc: 'myDescription'
}
};
const fn = () => {
throw errorObj;
}
expect(() => fn()).toThrowError(new Error(errorObj));
});
Run Code Online (Sandbox Code Playgroud)
这是笑话中的已知问题,请参阅https://github.com/facebook/jest/issues/8140
同时,这是我的解决方法 - https://github.com/DanielHreben/jest-matcher-specific-error
| 归档时间: |
|
| 查看次数: |
5555 次 |
| 最近记录: |