嘲笑单元测试函数抛出错误 [英] Jest unit testing a function throwing error

查看:78
本文介绍了嘲笑单元测试函数抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对节点中的某个函数进行单元测试,无论任何条件如何,该函数都会引发错误.这是我的节点函数定义.

I was trying to unit test a function in node which throws an error regardless of any condition. Here is my node function definition.

public testFunction() {
    throw new Error('Test Error');
}

如您所见,只要调用此函数,该函数始终会引发错误.我尝试使用jest .toThrow(error?)方法对该功能执行单元测试.我无法按预期进行单元测试.

As you can see this function always throws an error whenever it has been called. I tried to execute unit testing to this function using jest .toThrow(error?) method. I was not able to unit test the function as expected.

下面提到的是我编写的测试用例,并附有我在执行该测试用例时遇到的错误的屏幕截图.

The below mentioned are the test cases that I wrote and have attached the screenshot of the errors that I faced while executing the same.

测试用例#1

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction()).toThrow();
});

测试用例#2

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction).toThrow();
});

测试用例#3

来自博客,被提到

如果我们希望某个函数抛出某些异常 输入参数,关键是我们必须传递一个函数 定义而不在期望中调用我们的函数.

If we want to expect a function to throw an exception for certain input parameters, the key point is that we must pass in a function definition and not call our function inside the expect.

所以我将测试用例更新为

So I updated my test case as

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(() => testClass.testFunction()).toThrow();
});

但是它抛出了类似的错误

But it was throwing error like

我的实现有什么问题?单元测试将错误对象扔回去的函数的正确方法是什么?

What is the issue with my implementation? What is the correct method to unit test a function which throws an error object back?

推荐答案

您在第三次尝试中就正确了.唯一的问题是您将在测试定义中包括done回调.这告诉测试它是异步的,并且希望您在测试完成后调用done回调.

You had it right in your third attempt. The only problem is that you are including the done callback in the test definition. This tells the test that it is asynchronous and it expects you to call the done callback once the test has finished.

由于您的测试不是异步的,因此只需删除测试定义中的done回调即可.

As your test is not asynchronous, it should suffice with deleting the done callback in the test definition:

it('Should throw test error', () => {
    const testClass = TestClassService.getInstance();
    expect(() => testClass.testFunction()).toThrow();
});

这篇关于嘲笑单元测试函数抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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