我试图让TypeScript,mocha和chai在命令行上运行时一起工作。我正在使用TypeScript 0.9.1.1版本。使用Chai和TypeScript从命令行运行摩卡测试
我有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)
有什么方法可以查找柴的对象吗?
更新:这里有当导入注释掉会发生什么的详细信息:
如果我改变从DefinitelyTyped的chai.d.ts,使其开始
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__;
我相信,打字稿这里生成模块,因为我有进口声明。
谢谢,这让我又进了一步,但看到更新的问题。 –
您需要使用'--module commonjs'编译,而不是'--module amd' –
我建议不要更新chai.d.ts文件。在大多数项目中,TypeScript定义文件通过类似'tsd''(现在的''typings'')来管理。因此,其他项目成员可能会在每次回购时手动进行更新。相反,我建议你在你的仓库中保存一个独立的'.d.ts''并在那里定义任何附加模块。这将防止手动管理你对新的回购拉动的依赖。当然,你可以在这里添加来自这个答案的代码,这非常好。 –
Nicky