node.js - 运行测试时“描述未定义”

标签 node.js unit-testing mocha.js

使用 mocha 运行测试用例时出现以下错误

ReferenceError: describe is not defined
    at Object.<anonymous> (/myproject/test/unit/physicalperson.spec.js:12:1)

有人知道为什么会发生这种情况吗?

package.json

"scripts": {
    "test": "mocha"
  },

physicalperson.spec.js

const request = require('supertest-as-promised');
const chai = require('chai');
const app = require('../../src/server');

const expect = chai.expect;
const PHYSICALPERSON_ENDPOINT = '/api/physicalperson';

describe('Integration tests for Physical Person', () => {
  describe('\nFAIL Cases - Physical Person', () => {
    it('should return 404 status if physical person is not present on database', (done) => {
      request(app)
        .get(`${PHYSICALPERSON_ENDPOINT}/xxap`)
        .then((res) => {
          expect(res.statusCode).to.equal(404);
          done();
        })
        .catch((err) => {
          done(err);
        });
    });
  });
});

enter image description here enter image description here

我的尝试

我在 SO 中看到了一些帖子,我也尝试了下面的代码,但出现了同样的错误。

  var mocha = require('mocha')
  var describe = mocha.describe
  var it = mocha.it
  var assert = require('chai').assert

  describe('#indexOf()', function() {
    it('should return -1 when not present', function() {
      assert.equal([1,2,3].indexOf(4), -1)
    })
  })

最佳答案

我想,您正在使用 Node 命令运行测试,例如:node fileName.test.js 这是行不通的。要让 mocha 理解它是一个测试文件,您必须使用 mocha 命令运行它,如下所示。

mocha fileName.test.js

或者只需在 package.json 文件中进行配置,即可使用 **npm run test** 命令运行测试;示例如下。

"test": "istanbul cover --report cobertura --report html ./node_modules/mocha/bin/_mocha -- --reporter mocha-jenkins-reporter -t 180000 \"test/unit/*.js\"",

上述命令也生成 Istanbul 尔的覆盖率报告。

关于node.js - 运行测试时“描述未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47398837/

相关文章:

node.js - 从 Node.js 发出网络请求时如何指定网络接口(interface)?

unit-testing - Junit:拆分集成测试和单元测试

函数调用时Javascript模拟第三方 Node 库

node.js - 使用 grunt-mocha-test 创建测试组

reactjs - React 输入组件单元测试值始终未定义

javascript - 将 AngularJS 表导出到 .CSV,指向大约 :blank page?

mysql - docker-compose.yml问题nodejs和mysql

javascript - 使用 PM2 的 Nodejs 应用程序的启动顺序

.net - 在单元测试中使用 Entity Framework 是一个好习惯吗?

node.js - Mocha —— watch 和 Mongoose 模型