如何处理测试中函数抛出的异常/错误



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

// 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);
})
})

测试只是发送不带查询参数"value"的请求,因此函数init((将抛出错误。当我附上函数调用B"时;init";在try-catch块中的内部测试中,则测试通过,但如果没有try/catch块,则测试失败。我不想在测试中使用try-catch块,那么我该如何处理抛出的异常呢?

如果您正在投掷:

throw "Value missing in request";

然后你这样测试:

it("test on request", async()=>{
let bVal = new B();
await expect(bVal["init"]({})).rejects.toEqual("Value missing in request");
})

如果你这样扔:

throw new Error("Value missing in request");

然后你这样测试:

it("test on request error", async()=>{
let bVal = new B();
await expect(bVal["init"]({})).rejects.toThrow("Value missing in request");
})

最新更新