使用 Mocha 测试 NodeJS:'Require is not defined'

Testing NodeJS with Mocha: 'Require is not defined'

编辑:

根据对以下答案的评论:从 package.json 中删除“type”:“module”,据我所知,这正是让 Node 理解 'import' 和 'export' 的原因语句,并将所有内容还原为 'require' 和 'module.exports' 解决了问题。

有没有办法在保留 'import' 和 'export' 的同时让 Mocha 正常工作?


我有一个非常简单的节点文件,我正在尝试使用 Mocha/Chai 对其进行测试。实际代码很简单,这只是为了了解一点 Mocha 以及如何使用它。但是当我 运行 摩卡测试时,我得到错误 ERROR: ReferenceError: require is not defined `

我为遇到同样问题的人做了一些谷歌搜索,但我想出的例子是他们 运行 在浏览器中进行测试时(例如,参见 ) .

我要测试的文件,index.js


const argv = require('minimist')(process.argv.slice(2));


const digitTester = /\d/g;
const capTester = /[A-Z]/g;

const dict  = {
    length:10,
    must_have_numbers: true,
    must_have_caps: true
}

export default function passwordCheck(password) {
    if (!password) return false;
    if (typeof password !== "string") return false;
    if (password.length < dict.length) return false; // assumes that 10 is a MINIMUM length
    if (dict.must_have_numbers && !digitTester.test(password)) return false;
    return !(dict.must_have_caps && !capTester.test(password));

}
if (argv._.length) {
   console.log(passwordCheck(argv._[0]))
}

/**
 * alternate version to check a lot of passwords:
 *
 * if (argv._.length) {
 *  for (const pwd of argv_) console.log(passwordCheck(pwd)
 *}
 *
 */


mocha 文件,test/index.test.js



const chai = require('chai')
const expect = chai.expect

const passwordCheck = require('../index.js')

const tooShort = "A2a"
const noCaps = "a2abcdefghijklmnop"
const noNumber = "Aabcdefghijklmnop"
const good = "A2abcdefghijklmnop"

describe('password checking', () => {
  it('should return false for passwords less than length 10', () => {
    expect(passwordCheck(tooShort)).to.be.false;
  });
  it('should return false for passwords without a capital letter', () => {
    expect(passwordCheck(noCaps)).to.be.false;
  });
  it('should return false for passwords without a number', () => {
    expect(passwordCheck(noNumber)).to.be.false;
  });
  it('should return true for passwords that match criteria', () => {
    expect(passwordCheck(good)).to.be.true;
  });

});

package.json

{
  "name": "codetest",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "mocha"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "@types/minimist": "^1.2.1",
    "@types/node": "^14.14.20",
    "chai": "^4.2.0",
    "minimist": "^1.2.5",
    "mocha": "^8.2.1"
  }
}

错误信息是

✖ ERROR: ReferenceError: require is not defined
    at file:///Users/r/Documents/Projects/sandbox/pwd_checker/index.js:2:14
    at ModuleJob.run (node:internal/modules/esm/module_job:152:23)
    at async Loader.import (node:internal/modules/esm/loader:166:24)
    at async exports.handleRequires (/Users/r/Documents/Projects/sandbox/pwd_checker/node_modules/mocha/lib/cli/run-helpers.js:94:28)
    at async /Users/r/Documents/Projects/sandbox/pwd_checker/node_modules/mocha/lib/cli/run.js:341:25
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

节点 15.

从 package.json 中删除这一行 - "type": "module" 并检查它是否正常工作。

在测试前添加以下内容:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

这是因为您不能从 ESM 模块请求;有关详细信息,请参阅 this comment on a nodejs issue

文档:https://nodejs.org/api/esm.html#differences-between-es-modules-and-commonjs