【发布时间】:2018-08-27 14:06:49
【问题描述】:
我正在尝试使用 jasmine 为我的 angular5 Web 应用程序编写单元测试。
代码拆分成3个文件,分别是utilityFile.ts、component.ts和component.spec.ts
utilityFile.ts:
export class UtilityFile{
constructor(){}
parse(){
// do somthing
}
}
component.ts:
export class Component{
uf = new UtilityFile();
constructor(){}
runParse(){
uf.parse(); // <-- trying to test if this method has been called
}
}
component.spec.ts:
describe('test runParse()',()=>{
let comp:Component;
beforeAll(()=>{
comp = new Compnent();
comp.runParse();
})
it('should call uf.parse()', ()=>{
spyOn(comp.uf, 'parse');
expect(comp.uf.parse).toHaveBeenCalled(); // <-- test fails
})
})
相关包:
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
感谢每一个提示。
【问题讨论】:
-
你永远不会打电话给
comp.runParse。此外,您应该真正使用 Angular 的 DI(依赖注入)来提供UtilityFile到Component和TestBed来测试它(参见 angular.io/guide/testing)。 -
感谢您提供有关
comp.runParse的提示。我确实在我的真实代码中执行了这个调用。另一方面,我尝试了依赖注入。它没有用。通过调试组件的实例,我发现解析函数不是直接在comp.uf下,而是在comp.uf.__proto__.parser下。有什么想法吗? -
然后给出一个适当的minimal reproducible example 来说明实际问题。您发布的内容有明显的拼写错误,因此很难判断真正的问题是什么。
-
谢谢@jonrsharpe。在我准备正确的代码时,我找到了解决方案。
标签: angular unit-testing angular5 karma-jasmine