我已经创建了一个将数据发送到MailChimp的邮件列表。我想创建一个小型单元或集成测试,以验证它是否正常运行。我创建了一个POST路由,该路由获取用户的名字,姓氏,公司和电子邮件地址。我也有一个包含模拟用户和函数的帮助文件。问题是我不确定如何测试路由。测试通过了,但没有重定向到正确的路由。
signup.js
app.post('/signup', (req, res) => {
const {
firstName,
lastName,
company,
email
} = req.body
const data = {
members: [{
email_address: req.sanitize(email),
status: 'subscribed',
merge_fields: {
FNAME: req.sanitize(firstName),
LNAME: req.sanitize(lastName),
COMPANY: req.sanitize(company)
}
}]
}
const jsonData = JSON.stringify(data)
const options = {
url: 'https://us20.api.mailchimp.com/3.0/lists/539c805f12',
method: 'POST',
headers: {
Authorization: `auth ${MAILCHIMP_API_KEY}-us20`
},
body: jsonData
}
request(options, (err, response, body) => {
if (err) {
res.redirect('/')
} else {
if (response.statusCode === 200) {
req.flash('secondary', 'Thank you for signing up.')
res.redirect('/success')
} else {
res.redirect('/')
}
}
})
})
helper.js
module.exports.mockUser = {
firstName: 'John',
lastName: 'Doe',
company: 'Entivik',
email: 'jdoe@outlook.com'
}
module.exports.signupUser = async (agent, firstName, lastName, company, email) => agent
.post('/signup')
.set('content-type', 'application/x-www-form-urlencoded')
.send({
firstName,
lastName,
company,
email
})
test.spec.js
const chai = require('chai')
const chaiHttp = require('chai-http')
const should = chai.should()
const expect = chai.expect
const app = require('../../app')
const helper = require('./helper')
chai.use(chaiHttp)
describe('test submitted mailing list form', () => {
it('should return valid form input', async () => {
const agent = chai.request.agent(app)
await helper.signupUser(agent, helper.mockUser.firstName, helper.mockUser.lastName, helper.mockUser.company)
const res = await agent.get('/')
expect(res).to.have.status(200)
})
})