首页 > 解决方案 > 在 node.js 中需要 mocha 测试文件导致 TypeError: describe is not a function

问题描述

我有一个包含某些测试的测试文件:

describe("tests", () => {
  before(async () => {
    //....
  });
  afterEach(async () => {
    // ...
  });
});

我想在我的 node.js 代码中要求该文件:

const test = require(resolve('server.test'));
console.log(test);

但由于以下错误,它不起作用:

TypeError: describe is not a function

我试图从测试文件中导出一些东西,如下所示:

// in the test file
module.exports.name = 11;

describe("tests", () => {
 // ....
});

// in node.js 
const name = require(resolve('server.test'));
const t = JSON.stringify(name);
console.log(t);

我仍然遇到同样的错误

标签: javascriptnode.jsmocha.jschai

解决方案


我不确定您为什么要require在常规代码文件中测试文件,但如果您真的想要,您可以向全局命名空间对象describe添加一个函数,以便在需要您的测试文件时它存在:

if (global.describe === undefined) {  // if a global describe doesn't exist...
  global.describe = () => {};  // ...then define one
}
const test = require(resolve('server.test'));
console.log(test);

推荐阅读