簡體   English   中英

如何使用 mocha 測試帶有 Passport Google OAuth 身份驗證的 Express REST API?

[英]How to test an Express REST API with Passport Google OAuth authentication with mocha?

我正在構建一個應用程序,作為其中的一部分,我在 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 策略中使用“passport”,所以我無法向登錄頁面發送發布請求,也想不出登錄或驗證我的請求的方法。 (數據庫操作是Sequelize)。 如何在應用中測試 API 操作? 有標准的方法嗎?

我發現的問題的唯一解決方案是使用模擬護照身份驗證策略進行如下測試: https : //www.npmjs.com/package/passport-mocked並在您進行測試時使用該策略而不是您的策略環境。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM