Reputation: 291
I'm using NestJS with Jest and I get this error:
Matcher error: expected value must be a function
... when run following unit test.
I have set invalid email in mockBody
. Did I missed anything here?
app.service.ts
@Injectable()
export class UserService {
constructor(private emailService: EmailService) {}
async registerUserInquiry(user: UserDto): Promise<{ email: string }> {
try {
await sendEmail(user);
} catch (error) {
throw new HttpException('Something went wrong!', HttpStatus.BAD_REQUEST);
}
return {
email: user.email,
};
}
}
app.service.spec.ts
describe("registerUser()", () => {
it("Should throw bad request error when passing invalid data", async () => {
const mockBody: UserDto = {
name: "John Doe",
message: "Example inquiry message",
email: "@example",
mobile: "+60121234567",
};
expect(async () => await service.registerUserInquiry(mockBody)).toThrow(
new HttpException("Something went wrong!", HttpStatus.BAD_REQUEST)
);
});
});
email.config.ts
export const sendEmail = async (user: User) => {
const transporter = nodemailer.createTransport({
... // service & auth
});
const options = {
... // email info
};
await transporter.sendMail(options, function (error, info) {
try {
console.info(error);
return info;
} catch (error) {
console.error(error);
throw error;
}
});
};
Error:
Upvotes: 1
Views: 3053
Reputation: 31
try {
await service.registerUserInquiry(mockBody)
} catch(err) {
expect(err).toBeInstanceOf(BAD_REQUEST);
expect(err.message).toEqual{'Something went wrong!'}
}
Upvotes: 0
Reputation: 3451
Instead of this
expect(async () => await service.registerUserInquiry(mockBody)).toThrow(
new HttpException("Something went wrong!", HttpStatus.BAD_REQUEST)
);
Try this one
await expect(service.registerUserInquiry(mockBody)).rejects.toThrowError(...)
Your function is a promise which means it is not throwing an error but instead it rejects.
Upvotes: 3