【问题标题】:Jest: .toThrow matcher does not pass test on Error开玩笑:.toThrow 匹配器未通过错误测试
【发布时间】:2019-08-24 10:14:31
【问题描述】:

我想测试一个函数的无效输入并期望该函数抛出 在那个输入上。但是测试没有通过,但函数仍然抛出错误。我是个开玩笑的初学者,所以我不知道为什么会这样。

我的函数如下所示:

export class MyClass{
 static theFunction(tokens){
        let result = [];
        if (typeof tokens[0] === "string") {
            return tokens;
        } else {
            try {
                for(let token of tokens){
                    result.push(token.text);
                }
                return result;
            } catch (e) {
                throw new Error(e); //also tried throw e; and no try/catch aswell
            }
        }
    }
}}

Test.js:

import {MyClass} from './MyClass'
describe('Test the MyClass:', () => {
    test('invalid inputs for thefunction()',  () => {
        expect(MyClass.theFunction(0)).toThrow(/*'TypeError: tokens is not iterable'*/); 
        //Tried with and without the Error Message
    });
});

我错过了什么?

【问题讨论】:

    标签: javascript jestjs


    【解决方案1】:

    将您的函数包装在匿名函数中,以便 Jest 可以捕获错误:

    describe('Test the MyClass:', () => {
        test('invalid inputs for thefunction()',  () => {
            expect( () => { MyClass.theFunction(0) } ).toThrow();
        });
    });
    

    您可能想阅读有关 toThrow() in the Jest documentation 的部分,并查看 Github 上的 implementation in the Jest project

    【讨论】:

    • 谢谢。这样可行。我阅读了文档,但令我惊讶的是 Jest 没有将函数视为函数。但再次感谢你。现在知道了^^。
    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2020-04-01
    • 2018-08-05
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多