使用Jasmine测试Node应用程序的状态:200

Testing Node app with Jasmine for status: 200

本文关键字:状态 应用程序 Jasmine 测试 Node 使用      更新时间:2023-09-26

我正在为一个使用Node.js和Express构建的应用程序编写Jasmine测试。第一个测试之一是查看应用程序是否以200的statusCode响应。我一直在学习这个教程,它向你展示了如何做到这一点,但我遇到了一个障碍。

jasmine-node不会运行测试。没有任何故障;它就是不报告。显然,这是一个已知的错误。

然而,看看茉莉花节点项目,它已经一年多没有更新了!看看主要的茉莉花项目,我发现它现在支持Node!那么,是否放弃了jasmine-node,转而在jasmine中添加对Node的支持?在安装了jasmine并根据规范运行它之后,我现在遇到了一个新问题。当运行jasminenpm test时,我得到的不是Jasmine测试失败,而是

Started
TypeError: Cannot read property 'statusCode' of undefined

这是我的规范文件:

var request = require("request");
var base_url = "http://localhost:3000/";
describe("Hello World Server", function() {
  describe("GET /", function() {
    it("returns status code 200", function(done) {
      request.get(base_url, function(error, response, body) {
        expect(response.statusCode).toBe(200);
        done();
      });
    });
    it("returns Hello World", function(done) {
      request.get(base_url, function(error, response, body) {
        expect(body).toBe("Hello World");
        done();
      });
    });
  });
});

看起来您没有得到有效的响应。您应该在回调函数中查看error

request.get(base_url, function(error, response, body) {
    // Check for error
    if(error){
        console.log(error);
        // Probably assert a failure here.
    }
    expect(response.statusCode).toBe(200);
    done();
});

在使用console.log检查错误后,您可能不想删除日志记录并用一些茉莉花逻辑替换它来进行错误检查。