【问题标题】:Travis tests returning undefinedTravis 测试返回未定义
【发布时间】:2019-02-12 17:13:25
【问题描述】:

我正在使用 jasmine 进行测试,它在本地运行良好。然而,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”网址上吗?

【问题讨论】:

    标签: javascript express github jasmine travis-ci


    【解决方案1】:

    您似乎没有在任何地方启动您的服务器,因此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/other 的情况下发出请求。

    【讨论】:

    • 我在 heroku 上托管了应用程序并更新了 api 端点。现在可以使用了,谢谢
    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2012-10-31
    • 2020-07-29
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多