为什么摩卡找不到模块?找不到模块 'expect.js'

Why Mocha couldn't find module? Cannot find module 'expect.js'

我运行mocha test但是有错误

Error: Cannot find module 'expect.js'

我的package.json

{
  "name": "new-restexpress",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "start": "node index.js",
    "test": "PORT=3007 ./node_modules/.bin/mocha test -R spec"
  },
  "author": "Richard Rublev",
  "license": "ISC",
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-prettier": "^6.10.1",
    "eslint-plugin-prettier": "^3.1.3",
    "expect": "^25.3.0",
    "mocha": "^7.1.1",
    "prettier": "^2.0.4",
    "standard": "^14.3.3",
    "superagent": "^5.2.2"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongodb": "^2.2.36",
    "mongoskin": "^2.1.0",
    "morgan": "^1.10.0"
  }
}

我用 tree -d 查看

│   ├── expect
│   │   ├── build
│   │   │   └── ts3.4
│   │   ├── build-es5
│   │   └── node_modules
│   │       ├── ansi-styles
│   │       ├── color-convert
│   │       └── color-name

为什么无法识别 expect?

为了使用 expect 你必须安装一个允许你使用它的断言库,直接安装 expect 对我不起作用,我在遇到类似问题时安装了 chai。像这样安装:

npm i --save-dev chai

然后按下面的方式导入,这样使用:

var expect = require('chai').expect;
var numbers = [1, 2, 3, 4, 5];

expect(numbers).to.be.an('array').that.includes(2);

在 package.json 脚本中:

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

expect and expect.js 是两个不同的包。

第一个已安装,但您正在尝试使用第二个。

万一需要expect.js,只需运行npm install expect.js,你就可以解决了。