当我的控制器抛出错误时 Jest 显示未定义

Jest shows undefined when error is thrown from my controller

我有一个 Node 控制器来测试 Jest,我的目的是测试用户是否已经订阅了 Stripe:

controllers/userSubscriptionController.js
const userSubscription = async (req, res, next) => {
    const trowErr = true;
    if(throwErr){
       throw new Error("User has already subscribed.");
    }
}
module.exports = {userSubscription}

controllers/__tests__/userSubscriptionController.js
const {userSubscription} = require('../controllers/userSubscriptionController');
const { mockRequest, mockResponse, mockNext } = require("./interceptor");
let req = mockRequest();
let res = mockResponse();
let next = mockNext();
describe("My first test", async () => {
    it("should throws an error", () => {
        const s = await userSubscription(req, res, next)
        expect(s).toThrow()
    })
})

所以在启动测试时我收到了:

expect(received).toThrow(), Matcher error: received value must be a function , Received has value: undefined** 

为什么received有一个未定义的值导致测试失败?

在您的测试中,当 userSubscription 抛出任何值时,const s 未分配任何值,因此它是未定义的。

要测试您的 async 函数,您可以像这样编写测试

 describe('using returned promise', () => {
    it("should throws an error", () => {
      return expect(userSubscription(req, res, next)).rejects.toThrow('User has already subscribed')
    })
  })

或者像这样:

  describe('using await', () => {
    it("should throws an error", async () => {
      await expect(userSubscription(req, res, next)).rejects.toThrow('User has already subscribed')
    })
  })

https://repl.it/repls/AgreeableSlipperyHacks