在 jasmine 2.x 中,可以像这样检查函数被调用的次数(这当然是假设您正在监视所述函数):
expect(myservice.someFunction.calls.count()).toBe(someNumber);
在 TS 中写 Jasmine 测试与 JS 非常相似。据我所知,唯一真正的区别是语法。您现在将对变量进行强类型化,而不是使用函数来描述块,您将使用粗箭头语法。所以不是
describe('Test', function() {
it('true is true', function() {
expect(true).toBe(true);
})
})
你会这样写你的测试
describe('Test', () => {
it('true is true', () => {
expect(true).toBe(true);
})
})
这是我在 TS 中编写的一个小的人为测试示例。
namespace UserList.Services.Tests {
describe("UserList: GetEntityTypeService", () => {
let service: UserList.Services.GetEntityTypeService;
beforeEach(() => {
angular.mock.module("App.UserList.Module");
angular.mock.module(($provide: angular.auto.IProvideService) => {
$provide.service("UserList.Services.GetEntityTypeService", UserList.Services.GetEntityTypeService);
});
inject(($injector: angular.auto.IInjectorService) => {
service = <UserList.Services.GeteEntityTypeService>($injector.get("UserList.Services.GetEntityTypeService"));
});
});
it("should be defined", () => {
expect(service).toBeDefined();
});
});
}
记住 TS 是 JS 的超集。所以任何有效的 JS 都是有效的 TS。如果你真的想要,你可以用纯 JS 编写测试,它仍然可以工作。
至于你关于分离关注点的问题,我认为你是在正确的轨道上。这是我遵循的一个非常有效的模式。
- 用类型和名称描述对象。
- 加载对象的模块。
- 根据需要加载模拟模块。
- 注入依赖项并监视方法。
- 初始化对象:
- 只需注入服务即可。
- 使用 $controller 服务实例化控制器。
- 我们需要 $compile 指令。
- 将期望写入描述块中。
测试状态、对服务和事件的同步和异步调用,以及必要时的预期结果。