簡體   English   中英

使用Mocha和Supertest測試Node.js。 如何獲得該應用程序?

[英]Testing nodejs with mocha and supertest. How to get the app?

我正在嘗試用supertest測試一個nodejs應用程序,但我無法運行任何一條路由。 我已經把問題縮小了。 在測試文件中,我從以下內容開始:

var app = express();  // this is the problem, this isn't really the app, right?

// testing this dummy works fine, but I want the real one
app.get('/user', function(req, res){
  res.status(200).json({ name: 'tobi' });
});

describe('GET /user', function(){
  it('respond with json', function(done){
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  })
})

...此測試通過。 但是,當然,該虛擬/用戶路由不是我要測試的路由。 我想測試在./server.js中定義的“真實”應用程序中定義的路由。

即使我只是將虛擬的app.get('/user', function...定義)移至我用nodemon啟動的“真實” server.js文件中,該簡單測試也會失敗並顯示404。

那么,這行代碼實際上是做什么的: var app = express(); ,以及如何掌握在server.js文件中配置的app以便進行測試?

您需要從server.js export您的應用程序。 完成此操作后,您可以在測試文件中require該應用程序。

server.js

var express = require('express')

var app = express();

// Your routes here...

// At end of file
module.exports = app;

test.js (在test目錄中)

var api = require('../server.js'),
    request = require('supertest')(api);

describe('noshers', function() {

    it('doesn\'t allow GET requests', function(done) {
        request
            .get('/foo')
            .expect(405, done);
    });

});

暫無
暫無

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

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