使用mocha和supertest测试nodejs。如何获得应用程序?

时间:2016-02-22 21:11:26

标签: javascript node.js mocha supertest

我正在尝试使用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...定义移动到我的“真实”server.js文件,即我使用nodemon启动的那个文件,这个简单的测试失败了404.

那么这一行真正做了什么:var app = express();,以及如何掌握我的server.js文件中配置的app以便我可以测试它?

1 个答案:

答案 0 :(得分:1)

您需要export server.js来自require的应用。完成此操作后,您可以var express = require('express') var app = express(); // Your routes here... // At end of file module.exports = app; 测试文件中的应用。

server.js

test

test.js (在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); }); }); 目录中)

@if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif