Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 无法使用jasmine断言嵌套方法调用_Angular_Unit Testing_Angular5_Karma Jasmine - Fatal编程技术网

Angular 无法使用jasmine断言嵌套方法调用

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

我正在尝试使用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 = 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
    })
})