以下是Jest代码,用于测试节点代码(HapiJs端点)的实用程序功能(isAuthorized):
**Auth.js:**
export const isAuthorized = (request, h) =>
throw Boom.unauthorized('unauthorized')
**aut.test.js:**
import { isAuthorized } from './Auth';
test('it should return unauthorized', async () => {
const request = { };
expect(await isAuthorized(request)).toThrowError(/unauthorized/);
})
执行此测试时。它给出错误并跟踪指向函数实际上在Boom.unauthorized('some error')
处抛出.unauthorized
的位置。跟踪根本没有帮助,至少对我没有帮助...
问题是测试一个以合理预期抛出Boom错误的函数的最佳方法。
依赖项包括:
"hapi": "^18.1.0",
"jest": "^24.1.0",
"babel-jest": "^24.1.0",
"regenerator-runtime": "^0.13.1",
"@babel/cli": "^7.2.3",
"@babel/core": "^7.2.2",
"@babel/plugin-transform-runtime": "^7.2.0",
答案 0 :(得分:1)
根据Jest's docs,可以将toThrow
与一个类一起用作参数,这将检查引发的错误是否是该类的实例。因此,您可以(根据this进行验证):
const Boom = require('boom');
...
// mind `.rejects`
const rejected = expect(isAuthorized(request, h)).rejects;
rejected.toThrow(Boom);
rejected.toThrow('unauthorized');
答案 1 :(得分:0)
这对我有用:
import Boom from 'boom';
const isAuthorized = (request, h) => {throw Boom.unauthorized('unauthorized');};
test('should throw an error if unauthorized', () => {
const request = {};
expect(() => isAuthorized(request)).toThrowError(Boom.unauthorized('unauthorized'));
});