简体   繁体   English

Karma-Jasmine for.sort() 中的单元测试故障排除 Angular 中的 function

[英]Unit Testing Troubleshoot in Karma-Jasmine for .sort() function in Angular

I have a block of code written in Angular:我有一段用 Angular 编写的代码:

this.selectedData.sort((a, b) => {
        if (query === 'poll' && (a[query] === null || b[query] === null)) {
          return a[query] === null ? 1 : -1;
        } else if (query === 'submit') {
          return moment(a[query]).isBefore(moment(b[query])) ? 1 : -1;
        } else {
          return b[query].localeCompare(a[query]);
        }
});

I tried writing a callFake for the sort function like below:我尝试为排序 function 编写一个 callFake,如下所示:

spyOn(selectedData, 'sort').and.callFake((a, b) => {
     expect(query).toBe('poll');
});

But, the code-coverage shows, it is not going inside the sort function block.但是,代码覆盖率显示,它不会进入排序 function 块内。 Is there any other way of writing the test cases.有没有其他方法可以编写测试用例。 I also tried using callThrough() and it is showing me the same result.我也尝试使用 callThrough() ,它显示了相同的结果。

spyOn installs a spy onto an existing object but it does not invoke the specified method. spyOn将间谍安装到现有的 object 上,但它不调用指定的方法。 By chaining the spy with and.callFake , all calls to the spy will delegate to the supplied function instead of the object's method.通过使用and.callFake链接间谍,对间谍的所有调用都将委托给提供的 function 而不是对象的方法。 What you need is...你需要的是...

// Install spy (without delegating)     
spyOn(selectedData, 'sort');

// Invoke the object's method
const result = selectedData.sort(...);

// Compare actual result with expected result
expect(result).toBe(<expectedResult>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM