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

问题描述 投票:0回答:1

我有一个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 有一个未定义的值,使得测试失败?

javascript node.js jestjs tdd
1个回答
0
投票

在你的测试中,当 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.itreplsAgreeableSlipperyHacks。

© www.soinside.com 2019 - 2024. All rights reserved.