我试图在命令行上运行时让 TypeScript、mocha 和 chai 一起工作。我正在使用 TypeScript 版本 0.9.1.1。
我有CalculatorTest.ts:
/// <reference path="../definitions/mocha.d.ts" />
/// <reference path="../definitions/chai.d.ts" />
// import chai = require('node_modules/chai/chai');
var expect = chai.expect;
describe("Calculator", () => {
var calc: Calculator;
beforeEach(() => {
calc = new Calculator();
});
describe("Add", () => {
it("should have correct results", () => {
calc.add(1);
calc.add(2);
expect(calc.current()).to.equal(3);
});
it("this test should fail", () => {
expect(calc.current()).to.equal(10000);
});
})
});
我还有一个单独的 Calculator.js 文件。
我可以在带有页面的浏览器中正常运行:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Mocha Calculator Tests</title>
<link rel="stylesheet" href="scripts/node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="scripts/node_modules/mocha/mocha.js"></script>
<script src="scripts/node_modules/chai/chai.js"></script>
<script>mocha.setup('bdd')</script>
<script src="scripts/Calculator.js"></script>
<script src="scripts/test/CalculatorTest.js"></script>
<script>
mocha.checkLeaks();
mocha.globals(['jQuery']);
mocha.run();
</script>
</body>
</html>
但是,如果我尝试在命令行上运行
./node_modules/mocha/bin/mocha
或者
./node_modules/mocha/bin/mocha -r chai
我得到错误:
C:\javascript\Test\Test\scripts\test\CalculatorTest.
js:4
var expect = chai.expect;
^
ReferenceError: chai is not defined
at Object.<anonymous> (C:\javascript\Test\Test\scripts\test\CalculatorTest.js:4:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
有什么方法可以查找 chai 对象吗?
更新:以下是有关取消注释导入时会发生什么的更多信息:
如果我将chai.d.ts 从DefiniteTyped 更改为启动
declare module 'chai' {
并将文件中的前几行更改为:
/// <reference path="../definitions/mocha.d.ts" />
import chai = require('../definitions/chai');
var expect = chai.expect;
然后文件编译成功。
但是,当我从命令行运行时,我得到
% ./node_modules/mocha/bin/mocha
C:\javascript\Test\Test\scripts\test\CalculatorTest.js:2
define(["require", "exports", '../definitions/chai'], function(require, export
^
ReferenceError: define is not defined
at Object.<anonymous> (C:\javascript\Test\Test\scripts\test\CalculatorTest.js:2:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
生成的 JavaScript 文件开头为:
/// <reference path="../definitions/mocha.d.ts" />
define(["require", "exports", '../definitions/chai'], function(require, exports, __chai__) {
var chai = __chai__;
我相信 TypeScript 在这里生成了一个模块,因为我有 import 语句。