【发布时间】:2017-02-13 21:02:41
【问题描述】:
我正在构建一个应用程序,作为其中的一部分,我在 Express 上有一个 REST API,我想为其编写集成测试。我正在使用“mocha”和“chai-http”来执行此操作,除了添加身份验证之外,这一切都很好。所以在这样的测试中:
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()
})
})
})
})
我会收到错误消息,因为我的请求不是来自经过身份验证的会话。我正在使用带有 Google OAuth 策略的“护照”,因此我无法将发布请求发送到登录页面,并且我想不出登录或验证我的请求的方法。 (数据库操作是 Sequelize)。如何测试应用程序中的 API 操作?有标准方法吗?
【问题讨论】:
-
自创建此帖子以来,您是否有任何解决方案?
-
@vapurrmaid 是的,我已经添加了答案。
标签: node.js api tdd mocha.js passport.js