断言针对抛出的错误对象 [英] asserting against thrown error objects in jest

查看:59
本文介绍了断言针对抛出的错误对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抛出对象的函数,如何断言正确的对象是在开玩笑?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆