【问题标题】:cannot assert a nested method call with jasmine无法使用 jasmine 断言嵌套方法调用
【发布时间】:2018-08-27 14:06:49
【问题描述】:

我正在尝试使用 jasmine 为我的 angular5 Web 应用程序编写单元测试。

代码拆分成3个文件,分别是utilityFile.tscomponent.tscomponent.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(依赖注入)来提供 UtilityFileComponentTestBed 来测试它(参见 angular.io/guide/testing)。
  • 感谢您提供有关comp.runParse 的提示。我确实在我的真实代码中执行了这个调用。另一方面,我尝试了依赖注入。它没有用。通过调试组件的实例,我发现解析函数不是直接在comp.uf 下,而是在comp.uf.__proto__.parser 下。有什么想法吗?
  • 然后给出一个适当的minimal reproducible example 来说明实际问题。您发布的内容有明显的拼写错误,因此很难判断真正的问题是什么。
  • 谢谢@jonrsharpe。在我准备正确的代码时,我找到了解决方案。

标签: angular unit-testing angular5 karma-jasmine


【解决方案1】:

describe 块中的问题。

我必须创建 spy 并且 只有在那时我才调用了该函数。而在我的问题中,我调用了该函数,然后我创建了 spy 并断言它。

【讨论】:

    【解决方案2】:

    将您的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
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2012-08-24
      • 2013-10-01
      相关资源
      最近更新 更多