Mocha, “require is not defined” when test in browser

杀马特。学长 韩版系。学妹 提交于 2021-02-11 14:41:42

问题


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([])


回答1:


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



来源:https://stackoverflow.com/questions/50673993/mocha-require-is-not-defined-when-test-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!