【问题标题】:How to perform nodeJS integration tests with Jasmine?如何使用 Jasmine 执行 nodeJS 集成测试?
【发布时间】:2017-12-21 05:59:15
【问题描述】:

我有一个用 nodeJS 编写的服务器应用程序,用作 REST Api。对于单元测试,我使用 Jasmine,我还想使用一些模拟数据执行一些集成测试。像这样的测试:

从“../support/api-test-client”导入ApiTestClient;

import User from "../../src/model/user";

describe("GET /users", () => {

    it("returns an array with all users", done => {
        ApiTestClient
            .getUsers()
            .then(users => {
                expect(users).toEqual(jasmine.any(Array));
                done();
            })
            .catch(err => fail(err));
    });

});

通过正常的单元测试,我可以简单地模拟 API 调用,但在这种情况下,我必须首先运行服务器应用程序,打开 2 个终端,一个用于npm start,另一个用于npm test

到目前为止,我已经尝试将此预测试脚本添加到 package.json

"pretest": "node dist/src/server.js &"

所以进程在后台运行,但感觉不对,因为它会在测试套件结束后运行。

如何自动启动/停止服务器应用程序以运行此集成测试?

【问题讨论】:

  • 您是否使用任何框架来处理 REST 请求?难道不能用运行测试的同一个节点实例来处理请求吗?
  • 感谢@fonkap,我使用 Express 作为服务器应用程序,使用 Jasmine 进行测试,不涉及其他框架。你到底在暗示什么?
  • 抱歉耽搁了,我有点忙,但终于有时间写一个运行示例,希望对你有用。

标签: node.js jasmine automated-tests


【解决方案1】:

我找到了一种简单的方法,使用beforeEach 在套件之前启动express

注意:这是在 jasmine 2.6.0express 4.15.3 上测试的

小例子:

//server.js 
const express = require('express')
const app = express()

app.get('/world', function (req, res) {
  res.send('Hello World!')
})

app.get('/moon', function (req, res) {
  res.send('Hello Moon!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})



//spec/HelloSpec.js
var request = require("request");

describe("GET /world", function() {
  beforeEach(function() {
    //we start express app here
    require("../server.js");
  });


  //note 'done' callback, needed as request is asynchronous
  it("returns Hello World!", function(done) {
    request("http://localhost:3000/world", function(error, response, html){
      expect(html).toBe("Hello World!");
      done();
    });
  });

  it("returns 404", function(done) {
    request("http://localhost:3000/mars", function(error, response, html){
      expect(response.statusCode).toBe(404);
      done();
    });
  });

});

使用jasmine 命令运行它后,它会返回预期的结果:

Started
Example app listening on port 3000!
..


2 specs, 0 failures
Finished in 0.129 seconds

服务器关闭(3000端口也关闭)

我希望这会有所帮助。

【讨论】:

  • 这是否意味着服务器在每次测试期间都在启动/停止?
  • 它就像一个魅力,非常感谢。我把它放在 beforeAll 方法中,还删除了 .js 扩展,因为我使用了 TS
  • 我很高兴听到!不,它不是,它只为所有套件启动和停止一次。这就是我写两个测试的原因。
  • 这里关闭服务器是什么?
  • 服务器在执行测试的同一节点进程中运行,因此当该进程结束时服务器将关闭。我希望我在这里没有遗漏任何东西,但很容易检查服务器是否实际上正在关闭。
猜你喜欢
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
相关资源
最近更新 更多