Jest测试异步函数throw场景:toThrow匹配失效该如何解决?
问题原因
createContext是异步函数,执行后会返回Promise对象,内部抛出的错误只会让Promise转为rejected状态,不会同步抛出异常,因此同步的toThrow匹配器无法捕获到该错误。
修正后的测试代码
describe('Testing Apollo service file', () => { beforeAll(async () => { await mongoConnect() }) // 测试用例添加async标识支持await语法 test('test apollo context setup and configuration', async () => { const mockContext = { req: { headers: {} } } as ExpressContext // 搭配.rejects匹配器断言异步Promise的抛出结果 await expect(createContext(mockContext)).rejects.toThrow('UNAUTHORIZED') }) afterAll(async () => { await mongoDisconnect() }) })
补充说明
如果因为你抛出的是字符串而非Error实例导致toThrow匹配失效,可以将匹配语句替换为await expect(createContext(mockContext)).rejects.toEqual('UNAUTHORIZED')即可正常匹配。
内容的提问来源于stack exchange,提问作者SKeney
相关产品推荐
相关产品推荐

