摩卡,“要求未定义"在浏览器中测试时 [英] Mocha, "require is not defined" when test in browser

查看:45
本文介绍了摩卡,“要求未定义"在浏览器中测试时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Mocha 5.2.0、npm 6.1.0,我正在尝试在 Chrome 浏览器中进行测试.

但是当我运行测试时,浏览器显示require is not defined".

我想在浏览器中查看测试结果,但它在终端中有效.

我没有使用 webpack 等构建系统

test/test.js

var assert = require("assert");描述(数组",函数(){描述(#indexOf()",函数(){it("当值不存在时应该返回-1", function() {assert.equal([1,2,3].indexOf(4), -1);});});});

index.html

<预><代码>...<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.css" rel="stylesheet">...<身体><div id="mocha"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.js"></script><脚本>mocha.setup("bdd");<script src="test/test.js"></script><脚本>mocha.checkLeaks();摩卡.run();

package.json

<代码>{脚本":{测试":摩卡"}}

编辑 Karthikeyan

index.html

<script data-main="test/test.js" src="require.js"></script>

require.js:168 未捕获的错误:尚未为上下文加载模块名称assert":_.使用 require([])

解决方案

Require.js is missing .在导入 mocha.js 之前先将 require.js 导入你的体内

I'm using Mocha 5.2.0, npm 6.1.0, and I'm trying to test in Chrome browser.

But When I run the test, the browser says "require is not defined".

I want to see the test result in browser, but it works in terminal.

I'm not using build system like webpack etc.

test/test.js

var assert = require("assert");
    describe("Array", function() {
        describe("#indexOf()", function() {
            it("should return -1 when the value is not present", function() {
                assert.equal([1,2,3].indexOf(4), -1);
        });
    });
});

index.html

...
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.css" rel="stylesheet">
...
<body>
    <div id="mocha"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.js"></script>
    <script>
        mocha.setup("bdd");
    </script>

    <script src="test/test.js"></script>

    <script>
        mocha.checkLeaks();
        mocha.run();
    </script>
</body>

package.json

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

Edited Karthikeyan

index.html

<script data-main="test/test.js" src="require.js"></script>

require.js:168 Uncaught Error: Module name "assert" has not been loaded yet for context: _. Use require([])

解决方案

Require.js is missing . Import require.js inside your body before importing mocha.js

这篇关于摩卡,“要求未定义"在浏览器中测试时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆