node.js - 未捕获的断言错误 : expected 404 to equal 405

标签 node.js npm mocha.js chai

我正在尝试测试我正在运行的服务器。我需要做的是对服务器给出的响应进行 Mocha 测试。我对此很陌生,所以请原谅所犯的任何错误。

测试应该通过,但事实并非如此。我对此很陌生,所以我没有尝试过任何替代解决方案。谢谢。

在 Index.js 中我有:

console.log('index.js executing!');

var express = require('express');
var app = express();

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

app.get('/', function(req,res){
res.send('status.METHOD_NOT_ALLOWED');
});

var port = 3000;
app.listen(port,function() {
    console.log('Listening on port ' + port);
});

我正在用 Mocha 测试它:

console.log('test/test.js executing');

const chai = require('chai');
const expect = chai.expect;
const request = require('superagent');
const status = require('http-status');

const apiRoot = 'http://localhost:3000/';

describe('hello API', function(){
it('GET request returns text "Hello, World!".',function(done){
request.get(apiRoot)
    .end(function(err,res){
      expect(err).to.not.be.an('error');
      expect(res.statusCode).to.equal(status.OK);
      expect(res.text).to.equal('Hello, World!');
   done();
   });
});


it('POST request is not allowed',function(done){
 request.post(apiRoot)
   .end(function(err,res){
     expect(err).to.be.an('error');
     expect(res.statusCode).to.equal(status.METHOD_NOT_ALLOWED);
  done();
  });
 });
});

测试预计会通过。

我得到的实际结果是:

Uncaught AssertionError: expected 404 to equal 405
      + expected - actual

      -404
      +405

      at /home/plc/cs2410/test/test.js:26:27
      at Request.callback (node_modules/superagent/lib/node/index.js:826:3)
      at IncomingMessage.parser (node_modules/superagent/lib/node/index.js:1036:18)
      at endReadableNT (_stream_readable.js:1129:12)
      at processTicksAndRejections (internal/process/next_tick.js:76:17)

第 26 行和第 27 行是:

expect(res.statusCode).to.equal(status.METHOD_NOT_ALLOWED);
done();

最佳答案

您收到 404 错误是因为您的 Express 服务器未监听到该端点的 POST。如果您仔细观察,就会发现您已经为该端点定义了两个 GET 。您还使用 status.METHOD_NOT_ALLOWED 字符串响应第二个请求,而不是实际的 405 状态代码。您需要将第二个 app.get 更改为如下所示:

app.post('/', function(req,res){
  res.send(405, 'Method Not Allowed');
});

关于node.js - 未捕获的断言错误 : expected 404 to equal 405,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54561124/

相关文章:

javascript - 等待与 Mocha 未兑现的 promise

node.js - Express.js 应用程序的单元测试与集成测试

javascript - Restful api 末尾的 Id 问题

node.js - 为什么我不能将 @bundled-es-modules/chai 别名为 chai?

reactjs - 如何使用 React 渲染组件 onClick?

node.js - 将 HDR 照片从 iPhone 上传到网络 - GPS 数据丢失

javascript - $ 未在 mocha chai 测试脚本中定义

mysql - NodeJS mysql连接池与多个查询

javascript - jade 使用 javascript 变量(mongo 模型)

node.js - ionic 框架 : Ionic build fails while creating the project (v4. 12.0)