Travis测试返回未定义

时间:2018-09-07 10:52:17

标签: javascript express github jasmine travis-ci

我正在测试茉莉花,在本地工作正常。但是,Travis CI对于所有API测试都返回未定义。例子

4)服务器GET / api / v1 / orders状态200   信息:     预期未定义为200。   堆:     错误:预期的不确定值为200。         

测试摘要

  describe('GET /api/v1/orders', function () {
    var data = {};
    beforeAll(function (done) {
      Request.get('http://localhost:3001/api/v1/orders', function (error, response, body) {
        data.status = response.statusCode;
        data.body = JSON.parse(body);
        data.number = data.body.length;
        done();
      });
    });
    it('Status 200', function () {
      expect(data.status).toBe(200);
    });
    it('It should return three Items', function () {
      expect(data.number).toBe(3);
    });
  });

问题可能出在“ http://localhost:3001/api/v1/orders” URL吗?

1 个答案:

答案 0 :(得分:0)

您似乎没有在任何地方启动服务器,因此localhost:3001不可用。

一个好的解决方案是使用类似supertest的东西。它将允许您执行以下操作:

app.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const routes = require('./api/routes/routes.js')(app);

// We listen only if the file was called directly
if (require.main === module) {
    const server = app.listen(3001, () => {
        console.log('Listening on port %s...', server.address().port);
    });
} else {
// If the file was required, we export our app
    module.exports = app;
}

spec.routes.js

'use strict';

var request = require('supertest');

var app = require('../../app.js');

describe("Test the server", () => {
    // We manually listen here
    const server = app.listen();

    // When all tests are done, we close the server
    afterAll(() => {
        server.close();
    });

    it("should return orders properly", async () => {
        // If async/await isn't supported, use a callback
        await request(server)
            .get('/api/v1/orders')
            .expect(res => {
                expect(res.body.length).toBe(3);
                expect(res.status).toBe(200);
            });
    });
});

Supertest允许您在不依赖特定端口/ URL /其他的情况下发出请求。