简体   繁体   中英

Requiring mocha test file in node.js cause TypeError: describe is not a function

I have a test file containing certain test :

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

And i want to require that file inside my node.js code:

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

but it's not working because of the following error :

TypeError: describe is not a function

I tried to export something from inside the test file like this :

// 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);

I'm still getting the same error

I'm not sure why you want to require a test file in a regular code file, but if you really want to you can add a describe function to the global namespace object so it exists when your test file is required:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM