【问题标题】:'Describe is not defined' when running my test运行我的测试时“未定义描述”
【发布时间】:2018-05-04 01:47:57
【问题描述】:

使用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);
        });
    });
  });
});

我的尝试

我在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)
    })
  })

【问题讨论】:

  • 我不确定您是否看过以下问题,似乎是一个热门问题stackoverflow.com/questions/28400459/…
  • @loulala 是的,我看到了这个线程和其他线程,但仍然无法正常工作。我用我的尝试更新了我的问题
  • 您用来运行测试的确切命令是什么?
  • @Louis npm test,在 package.json 中我输入了"scripts": { "test": "mocha" } ,但我也尝试过"test": "node ./node_modules/mocha/bin/mocha"
  • 我不明白你回复的后半部分。很明显,您没有调用测试(即通过 mocha),而是将文件作为 JS 文件运行。当然那是行不通的。查看有关如何运行测试的 mocha 文档。

标签: node.js unit-testing mocha.js


【解决方案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 生成覆盖率报告。

【讨论】:

    猜你喜欢
    • 2019-08-12
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多