Express.js,Jest,Supertest:测试跑步者查找路由处理程序时遇到麻烦

时间:2019-02-23 12:02:17

标签: node.js express jestjs supertest

我正在尝试使用Jest和Supertest在Express服务器上设置测试。这是我的测试和目标代码:

// routes/index.js
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});



// index.test.js
const request = require('supertest');
const express = require('express');

const app = require('express');
const router = require('../index').router;


test('GET /', (done) => {
  request(router)
    .get('http://localhost:4000')
    // .set('Accept', 'application/json')
    .expect(200)
    .end((err, res) => {
      if (err) throw err;
      done();
    })
});

开玩笑给我以下错误:

expected 200 "OK", got 404 "Not Found"

      at Test.Object.<anonymous>.Test._assertStatus (node_modules/supertest/lib/test.js:268:12)
      at Test.Object.<anonymous>.Test._assertFunction (node_modules/supertest/lib/test.js:283:11)
      at Test.Object.<anonymous>.Test.assert (node_modules/supertest/lib/test.js:173:18)
      at Server.localAssert (node_modules/supertest/lib/test.js:131:12)

也尝试过:相对网址('/')。 Error: Can not read property "apply" of undefined

导入在route / index.js中导出的​​路由器对象,如下所示:

const router = require('../index').router;  
// TypeError: Cannot read property 'address' of undefined 
// (while pointing at the .get() method)

我怀疑我引入Router()的方式可能不正确,但是我的直接尝试没有成功。

有人知道这个问题吗?

1 个答案:

答案 0 :(得分:0)

通过要求app.js并将其传递给请求来解决:

const app = require("../../app");

test('GET /cold-start', (done) => {
  request(app)
    .get('/')
    .set('Accept', 'application/json')
    .expect(200)
    .end((err, res) => {
      if (err) throw err;
      done();
    })
});