我已经为一个项目设置了一个小测试环境。它应该使用 mocha
和 chai
进行单元测试。我已经设置了一个 html
文件作为测试运行程序:
<!DOCTYPE html>
<html>
<head>
<title>Mocha Tests</title>
<link rel="stylesheet" href="node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="node_modules/mocha/mocha.js"></script>
<script src="node_modules/chai/chai.js"></script>
<script>mocha.setup('bdd')</script>
<script src="test/chaiTest.js"></script>
<script>mocha.run();</script>
</body>
</html>
chaiTest.js
文件包含这个简单的测试:
let assert = chai.assert;
describe('simple test', () => {
it('should be equal', () => {
assert.equal(1, 1);
});
});
当我现在在浏览器中调用测试运行程序时,结果会正确显示。效果很好。但是当我在控制台上运行 mocha
时,它告诉我 chai 未定义
。
因此,为了使其在控制台中正常工作,我只需在测试文件的第一行添加 chai
的 require
即可。
let chai = require('chai');
现在测试在控制台中运行良好,但是当我在浏览器中执行测试时,它告诉我 require
是 undefined
。
我知道,这些错误在这里完全有道理!它们是未定义的。但是有没有办法用 mocha
和 chai
编写测试并让它们在浏览器和控制台中执行?
我知道我可以为浏览器和控制台创建两个测试文件。但这很难维持。所以我想编写一个测试文件,在两种环境中正确执行......
最佳答案
我现在自己找到了解决方案。需要使用chai
的配置文件。就像我的例子一样,我将其命名为 chaiconf.js
。在此文件中可以写入 chai
的默认设置。每次测试之前都需要此文件。
我的chaiconf.js
:
let chai = require("chai");
// print stack trace on assertion errors
chai.config.includeStack = true;
// register globals
global.AssertionError = chai.AssertionError;
global.Assertion = chai.Assertion;
global.expect = chai.expect;
global.assert = chai.assert;
// enable should style
chai.should();
现在将此配置附加到每个测试中。为此,在 package.json
中创建一个脚本条目:
"scripts": {
"test": "mocha --require chaiconf.js"
},
现在,每当您在控制台中使用 npm test
时,在测试之前都需要 chaiconf.js
并使 chai
全局可用,例如在浏览器中。
无需配置文件的另一种方法是使用内联决策来接收 chai
:
let globChai = typeof require === 'undefined' ? chai : require('chai');
关于javascript - 可以在控制台和浏览器中在单个测试文件中使用 chai 运行 Mocha 测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42857544/