[英]TypeError when Mocking a Node Module with Jest
这里我有一个文件 mail.js,它发送 email
const nodemailer = require('nodemailer')
const mailGun = require('nodemailer-mailgun-transport')
const auth = {
auth: {
api_key: process.env.MAILGUN_API_KEY,
domain: process.env.DOMAIN
}
}
const transporter = nodemailer.createTransport(mailGun(auth))
const mailTo = (name, email) => {
const mailOptions = {
from: 'example@icloud.com',
to: 'cm@example.com',
subject: 'Welcome!',
text: `Hey, ${name}! Thanks for joining Task Manager!`
}
transporter.sendMail(mailOptions)
}
module.exports = mailTo
我正在尝试进行 Jest 测试,我需要模拟 nodemailer 和 mailGun 函数,所以每次运行测试时我都不会得到 email。 所以我创建了一个__mocks__
文件夹并将我的 2 个模拟模块放在__mocks__/nodemailer.js
和__mocks__/nodemailer-mailgun-transport.js
中。 这是那些文件
//nodemailer.js
module.exports = {
createTransport() {
},
sendMail() {
}
}
//nodemailer-mailgun-transport.js
module.exports = {
mailGun() {
}
}
这是我的测试
const request = require('supertest')
const jwt = require('jsonwebtoken')
const mongoose = require('mongoose')
const app = require('../src/app')
const User = require('../src/models/user')
const userOneId = mongoose.Types.ObjectId()
const userOne = {
_id: userOneId,
name: 'Jon',
email: 'jon@example.com',
password: 'JonTest123',
tokens: [{
token: jwt.sign({ _id: userOneId }, process.env.JWT_SECRET)
}]
}
beforeEach(async () => {
await User.deleteMany()
await new User(userOne).save()
})
test('Should signup a new user', async() => {
const response = await request(app).post('/users').send({
name: 'Caleb',
email: 'caleb@example.com',
password: 'TestPass637!'
}).expect(201)
//Assert that the database was changed correctly
const user = await User.findById(response.body.user._id)
expect(user).not.toBeNull()
//Assertions about the response
expect(response.body).toMatchObject({
user: {
name: 'Caleb',
email: 'caleb@example.com'
},
token: user.tokens[0].token
})
expect(user.password).not.toBe('TestPass637!')
})
我有 Jest 设置来查找测试目录中的__mocks__
文件,这是我拥有它的地方
但是当我运行测试时,我得到TypeError: mailGun is not a function
为什么它不能识别 mailGun() function?
nodemailer-mailgun-transport
应该返回 function 以便您可以将auth
传递给它。 在您的测试代码中, mailGun
指的是默认的 output,而不是属性。
//nodemailer-mailgun-transport.js
module.exports = (auth) => {
// do something with auth, if you want
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.