javascript - 使用 Jasmine 和 TypeScript 进行单元测试

标签 javascript unit-testing typescript jasmine chutzpah

我正在尝试使用 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-nodejasmine 版本。这比使用全局安装的版本要好,因为使用本地版本,您可以确保每个人都使用相同的版本。

注意:如果你有一个网络应用程序而不是节点应用程序,你应该使用 Karma 而不是 Jasmine CLI 来运行你的测试。

关于javascript - 使用 Jasmine 和 TypeScript 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863565/

相关文章:

unit-testing - 单元测试并发软件 - 你做什么?

javascript - 如何从 Angular 的 api 在单选组中使用 ngModel

javascript - 限制在给定时间打开的 promise 数量

javascript - 仅当监听器存在时才发布消息?

javascript - Browserify - 全局变量

java - 处理状态为 NO_CONTENT 的响应时的 Spring RestTemplate 行为

javascript - 是否可以在 Styles.scss 中动态导入 Variables.scss 文件?

javascript - 重定向后如何更新组件的状态?

javascript - 将多个结果保存在本地存储中

c# - 测试一种发送电子邮件但不发送邮件的方法