我正在尝试使用 Jasmine 编译用 Typescript 编写的单元测试。对于我的单元测试文件中的以下内容,Resharper 会提示我提供一个从 jasmine.d.ts 导入类型的链接。
/// <reference path="sut.ts" />
/// <reference path="../../../scripts/typings/jasmine/jasmine.d.ts" />
describe("Person FullName", function () {
var person;
BeforeEach(function () {
person = new Person();
person.setFirstName("Joe");
person.setLastName("Smith");
});
It("should concatenate first and last names", function () {
Expect(person.getFullName()).toBe("Joe, Smith");
});
});
所以我点击链接并得到以下结果(实际上 resharper 只在 describe 函数前加上“Jasmine.”前缀,所以我手动在其他 Jasmine 调用前加上前缀):
/// <reference path="sut.ts" />
/// <reference path="../../../scripts/typings/jasmine/jasmine.d.ts" />
import Jasmine = require("../../../Scripts/typings/jasmine/jasmine");
Jasmine.describe("Person FullName", function () {
var person;
Jasmine.BeforeEach(function () {
person = new Person();
person.setFirstName("Joe");
person.setLastName("Smith");
});
Jasmine.It("should concatenate first and last names", function () {
Jasmine.Expect(person.getFullName()).toBe("Joe, Smith");
});
});
然而,导入语句有一条红色波浪线,错误消息为“无法解析外部模块 ../../../scripts/typings/jasmine/jasmine。模块不能别名为非模块类型”
知道是什么导致了这个错误吗?我检查过“模块系统”选项在我的项目build设置中设置为 AMD。我还检查了 jasmine 模块是否在 jasmine.d.ts 中定义。我从 DefinitelyTyped 网站下载了这个文件。
declare module jasmine {
...
}
最佳答案
这是(在我看来)截至 2018 年测试 ts-node
应用程序的最佳方法:
npm install --save-dev typescript jasmine @types/jasmine ts-node
在 package.json
中:
{
"scripts": {
"test": "ts-node node_modules/jasmine/bin/jasmine"
}
}
在 jasmine.json
中将文件模式更改为 *.ts
"spec_files": ["**/*[sS]pec.ts"],
在你的规范文件中:
import "jasmine";
import something from "../src/something";
describe("something", () => {
it("should work", () => {
expect(something.works()).toBe(true);
});
});
运行测试:
npm test
这将使用本地安装的 ts-node
和 jasmine
版本。这比使用全局安装的版本要好,因为使用本地版本,您可以确保每个人都使用相同的版本。
注意:如果你有一个网络应用程序而不是节点应用程序,你应该使用 Karma 而不是 Jasmine CLI 来运行你的测试。
关于javascript - 使用 Jasmine 和 TypeScript 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863565/