I have a Node controller to test with Jest, my aim is to test if user has already a Stripe subscription:
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()
})
})
So when launching the test I received:
expect(received).toThrow(), Matcher error: received value must be a function , Received has value: undefined**
Why received has an undefined value that makes the test fail?
In your test when the userSubscription
throws no value is assigned to the const s
so it's undefined.
To test your async
function you can write the test like this
describe('using returned promise', () => {
it("should throws an error", () => {
return expect(userSubscription(req, res, next)).rejects.toThrow('User has already subscribed')
})
})
or like this:
describe('using await', () => {
it("should throws an error", async () => {
await expect(userSubscription(req, res, next)).rejects.toThrow('User has already subscribed')
})
})