代码之家  ›  专栏  ›  技术社区  ›  josemigallas

如何使用Jasmine执行nodeJS集成测试?

  •  0
  • josemigallas  · 技术社区  · 7 年前

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

    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调用,但在这种情况下,我必须首先运行服务器应用程序,打开两个终端,一个用于 npm start 然后是另一个 npm test .

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

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

    因此,该过程在后台运行,但感觉不太好,因为它将在测试套件结束后运行。

    1 回复  |  直到 7 年前
        1
  •  1
  •   fonkap    7 年前

    我找到了一个简单的方法来使用 beforeEach 开始 express 在套房前。

    jasmine 2.6.0 express 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也关闭)

    我希望这有帮助。