0

我已经为一个项目设置了一个小测试环境。它应该使用mochaandchai进行单元测试。我已经设置了一个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');

现在测试在控制台中运行良好,但是当我在浏览器中执行测试时,它告诉我requireundefined.

我知道,这些错误在这里完全有道理!它们是未定义的。但是有没有办法用mochaand编写测试chai并让它们在浏览器和控制台中执行?

我知道我可以为浏览器和控制台创建两个测试文件。但这将很难维持。所以我想写一个测试文件,在两种环境中都能正确执行......

4

1 回答 1

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');
于 2017-03-17T13:01:57.590 回答