Angular 无法使用jasmine断言嵌套方法调用
我正在尝试使用jasmine为我的angular5 web应用程序编写单元测试 代码分为3个文件,即Angular 无法使用jasmine断言嵌套方法调用,angular,unit-testing,angular5,karma-jasmine,Angular,Unit Testing,Angular5,Karma Jasmine,我正在尝试使用jasmine为我的angular5 web应用程序编写单元测试 代码分为3个文件,即utilityFile.ts、component.ts和component.spec.ts utilityFile.ts: export class UtilityFile{ constructor(){} parse(){ // do somthing } } 组件1.ts: export class Component{ uf = ne
utilityFile.ts
、component.ts
和component.spec.ts
utilityFile.ts:
export class UtilityFile{
constructor(){}
parse(){
// do somthing
}
}
组件1.ts:
export class Component{
uf = new UtilityFile();
constructor(){}
runParse(){
uf.parse(); // <-- trying to test if this method has been called
}
}
感谢您的每一个提示。描述
块中的问题
我必须创建spy
,然后才能调用该函数。而在我的问题中,我调用函数,然后创建spy
并断言它。将spy
移动到beforeAll
块,在那里调用runParse()
。因为runParse()
首先调用uf.parse()
,当时没有创建用于监视的spy
。因此,应该在调用spy之前创建它
describe('test runParse()',()=>{
let comp:Component;
beforeAll(()=>{
comp = new Compnent();
spyOn(comp.uf, 'parse'); // create spy before calling runParse()
comp.runParse();
})
it('should call uf.parse()', ()=>{
expect(comp.uf.parse).toHaveBeenCalled(); // should pass now
})
})
您从不调用comp.runParse
。此外,您应该真正使用Angular的DI(依赖项注入)向组件提供实用文件,并使用测试台测试它(请参阅)。感谢您提供有关comp.runParse
的提示。在我的真实代码中,我确实在中执行这个调用。另一方面,我尝试了依赖注入。它不起作用。通过调试组件的实例,我发现parse函数不是直接位于comp.uf
下,而是位于comp.uf.\uuuu proto\uuuu.parser
下。有什么想法吗?然后给出一个恰当的例子来说明实际问题。你发布的内容有明显的打字错误,所以很难说真正的问题是什么。谢谢@jornsharpe。当我准备正确的代码时,我找到了解决方案。
"@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",
describe('test runParse()',()=>{
let comp:Component;
beforeAll(()=>{
comp = new Compnent();
spyOn(comp.uf, 'parse'); // create spy before calling runParse()
comp.runParse();
})
it('should call uf.parse()', ()=>{
expect(comp.uf.parse).toHaveBeenCalled(); // should pass now
})
})