首页 > 解决方案 > 如何使用 JS 脚本在同一个文件中运行 mocha

问题描述

是否可以将 JS 代码和 mocha 测试放在同一个文件中?目的是当您只想玩一些东西、学习 JS、准备面试等时,将实现和测试放在同一个文件中。

该文件将在 VSCode 中使用 Debug (F5) 执行。

function increment(n) {
return n + 1;
}

mocha.setup("bdd");
const { assert } = chai;

describe('Array', function () {
    describe('#indexOf()', function () {
        it('should increment', function () {
            assert.equal(increment(1), 2);
        });
    });
});

mocha.run();

尝试运行此示例,这是您在浏览器中运行 mocha 测试的方式,我收到错误“mocha 未定义”

我运行了“npm install --save-dev mocha”和“npm install --save-dev chai”。该文件是 test1.js。在 app.js 中,我有“require(”./test1")”。启动配置为:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Program",
            "program": "${workspaceFolder}/app.js",
            "request": "launch",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "type": "pwa-node"
        }
    ]
}

标签: javascriptunit-testingvisual-studio-codemocha.js

解决方案


经过更多谷歌搜索后,我找到了解决方案,您的 Debug launch.json 文件必须具有以下配置。基本上你需要启动的程序是“${workspaceFolder}/node_modules/mocha/bin/_mocha”。

你的 JS 文件中不需要任何 mocha 命令: mocha.setup("bdd"); 摩卡运行();

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Mocha Tests",
            "type": "pwa-node",
            "request": "launch",
            "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
            "args": [
                "-u",
                "bdd",
                "--timeout",
                "999999",
                "--colors",
                "${workspaceFolder}/thon-ly-40-questions"
            ],
            "skipFiles": [
                "<node_internals>/**"
            ],
        },
    ]
}

推荐阅读