我为项目设置了一个小测试环境。它应该使用select work_status, paid, from_date, to_date, is_reset,
count(is_reset) OVER (ORDER BY work_status, paid, from_date) AS grp
from c1
和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
现在测试在控制台中运行正常,但是当我在浏览器中执行测试时,它告诉我let chai = require('chai');
是require
。
我知道,这些错误在这里完全有意义!他们是未定义的。但有没有办法用undefined
和mocha
编写测试并让它们在浏览器和控制台中执行?
我知道我可以为浏览器和控制台创建两个测试文件。但这很难维持。所以我想编写一个测试文件,在两种环境中都能正确执行......
答案 0 :(得分:1)
我现在自己找到了一个解决方案。需要使用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');