【问题标题】:How to handle exception/error thrown from function in test?如何处理测试中函数抛出的异常/错误?
【发布时间】:2022-10-14 02:35:25
【问题描述】:

我正在为一个功能编写测试。这是文件-

// A.ts
export abstract class A{
    protected abstract method();
}

//B.ts
export class B extends A{
    constructor(){  super();  }

protected async method(){
    init(request);
    //some more method calls
}

private async init(request){
    try {
        const reqUrl = new URL('http://localhost' + request.url);
        let param = reqUrl.searchParams.get("value") || "";
        if (!param) {
            throw "Value missing in request";
        }
        someFunc();
    }
    catch (e) {
        console.log(e);
        throw e;
    }
}
}

//B.spec.ts
describe("tests", ()=> {
    afterEach(() =>{
        jest.resetAllMocks();
        jest.clearAllMocks();
    })
    it("test on request", async()=>{
        let bVal = new B();
        let socket = new Socket();
        let request = new IncomingMessage(socket);
        await B["init"](request);
        socket.destroy();
        const spied = jest.spyOn(util,'someFunc').mockImplementation(()=>{});
        expect(spied).toBeCalledTimes(0);
    })
})

测试只是发送没有查询参数“值”的请求,因此函数 init() 将抛出错误。当我将函数调用 B"init" 包含在 try catch 块中的 test 中时,测试通过但没有 try catch 块,它失败了。 我不想在我的测试中使用 try catch 块,那么如何处理抛出的异常?

【问题讨论】:

    标签: unit-testing error-handling jestjs mocking ts-jest


    【解决方案1】:

    尝试这样的事情:

    it('should test init', async () => {
      await expect(init()).rejects.toThrow("Cannot read properties of undefined (reading 'url')");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-04
      • 2011-04-07
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 2019-11-26
      • 2011-11-23
      • 2013-01-21
      相关资源
      最近更新 更多