Mocha js Uncaught TypeError: Cannot read properties of undefined (reading 'should')

Mocha js Uncaught TypeError: Cannot read properties of undefined (reading 'should')

所以我正在尝试测试我的 API 和 mocha js,但我遇到了这个错误。

SAMPLE unit test
1) should return posts with tag tech sorted by likes


0 passing (26ms)
1 failing

1) SAMPLE unit test
  should return home page:
  Uncaught TypeError: Cannot read properties of undefined (reading 'should')
  at Test.<anonymous> (test\get_info.test.js:22:18)
  at Test.assert (node_modules\supertest\lib\test.js:172:8)
  at localAssert (node_modules\supertest\lib\test.js:120:14)
  at C:\Users\tiktk\Desktop\Fetch\node_modules\supertest\lib\test.js:125:7
  at Test.Request.callback (node_modules\superagent\lib\node\index.js:927:3)
  at ClientRequest.<anonymous> (node_modules\superagent\lib\node\index.js:844:12)
  at ClientRequest.emit (node:events:390:28)
  at Socket.socketErrorListener (node:_http_client:447:9)
  at Socket.emit (node:events:390:28)
  at emitErrorNT (node:internal/streams/destroy:157:8)
  at emitErrorCloseNT (node:internal/streams/destroy:122:3)
  at processTicksAndRejections (node:internal/process/task_queues:83:21)

我已经安装了所有依赖项并且是最新的,但我仍然收到该错误。

var supertest = require("supertest");
var should = require("should");

var server = supertest.agent("http://127.0.0.1:3000");

describe("Api unit test",function(){

  it("should return posts with tag tech sorted by likes",function(done){

    server
    .get("/api/posts?tags=tech&sortBy=likes&direction=desc")
    .expect("Content-type",/json/)
    .expect(200) 
    .end(function(res){
      // HTTP status should be 200
      res.status.should.equal(200);
      // Error key should be false.
      res.body.error.should.equal(false);
      done();
    });
  });
});

link 应该 return 数组中的一堆对象作为按喜欢排序的 JSON 文件(在本例中)

错误很可能是由于 res.body.error 在您没有错误的情况下未定义。在这种情况下,您的测试应该类似于:

res.body.should.not.have.property('error')

为了证实我的假设,在检查错误之前,您应该console.log res.body 的内容。