[英]Possible to run mocha test with chai in console and browser within a single test file?
我已经为项目设置了一些测试环境。 应该使用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 is not defined
。
因此,要使其在控制台中正常工作,我只require
在测试文件的第一行中添加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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.