I'm building an app and as part of it, I have a REST API on Express that I would like to write integration tests for. I'm using "mocha" and "chai-http" to do this and it all works well aside from when I add authentication. So in a test like:
process.env.NODE_ENV = 'development'
let chai = require('chai')
let chaiHttp = require('chai-http')
let should = chai.should()
var server = require('../app.js')
var schemas = require('../schemas')
var Snippet = schemas.Snippet
chai.use(require('chai-passport-strategy'))
chai.use(chaiHttp)
describe('Snippet', () => {
beforeEach((done) => {
Snippet.destroy({
where: {}
}).then(function () {
done()
}).catch(function (e) {
done(e)
})
})
describe('snippet create', () => {
it('it should store a snippet ', (done) => {
let snippet = {
title: 'Test',
description: 'Mock description',
snippet: 'Mock body',
keywords: 'Test key, words;input',
type: 'sql',
rating: 1,
approved: false
}
chai.request(server)
.post('/api/submitSnippet/')
.send(snippet)
.end((err, res) => {
if (err) console.log(err)
res.should.have.status(200)
res.body.should.be.a('object')
res.body.should.have.property('title')
res.body.should.have.property('description')
res.body.should.have.property('snippet')
res.body.should.have.property('keywords')
res.body.should.have.property('type')
res.body.should.have.property('rating')
res.body.should.have.property('approved')
res.body.title.should.equal('Test')
res.body.description.should.equal('Mock description')
res.body.snippet.should.equal('Mock body')
res.body.keywords.should.equal(['Test', 'key', 'words', 'input'])
res.body.type.should.equal('sql')
res.body.rating.should.equal(1)
res.body.approved.should.equal(false)
done()
})
})
})
})
I would get an error because my request won't come from an authenticated session. I am using "passport" with Google OAuth strategy so I can't send a post request to a login page and I can't think of a way to log in or authenticate my requests. (The database operations are Sequelize). How can I test the API operations in the app? Is there a standard approach?
我发现的问题的唯一解决方案是使用模拟护照身份验证策略进行如下测试: https : //www.npmjs.com/package/passport-mocked并在您进行测试时使用该策略而不是您的策略环境。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.