在 Jest expect 中处理 Boom 错误时无法理解错误

unable to understand the error when handling Boom error in Jest expect

以下是 Jest 代码,用于测试 Node 代码(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。跟踪根本没有帮助,至少对我来说没有...

问题是测试在 Jest expect 中抛出 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",

根据Jest's docs you can use toThrow with a class as argument, which will check whether the thrown error is an instance of this class. So you can (verified accordingly to this):

const Boom = require('boom');
...
// mind `.rejects`
const rejected = expect(isAuthorized(request, h)).rejects;
rejected.toThrow(Boom);
rejected.toThrow('unauthorized');

这个,对我有用:

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