角单位测试错误:预期的间谍getDateFormat被称为
我是对单位测试的新手,希望有人帮助我。 我有一个称为StudentComponent的角组件,并且具有以下内容。
public getAllStudents(){
this.apollo.query({
query: GETALL_STUDENTS,
}).subscribe((result: any) => {
this.students = result?.data?.getAllStudents;
this.students.forEach(element => {
element.Age = this.CalculateAge(element.DateOfBirth);
element.DateOfBirthString = this.getDateFormat(element.DateOfBirth);
});
});
}
public CalculateAge(dateOfBirth: any): number {
let age = 0;
if (dateOfBirth) {
var timeDiff = Math.abs(Date.now() - new Date(dateOfBirth).getTime());
age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
}
return age;
}
getDateFormat(date: Date): string{
let dateString = ""
if(date){
dateString = formatDate(date, 'yyyy/MM/dd','en_US').toString();
}
return dateString;
}
我写了测试案例,如下说
describe('getAllStudents', () => {
it('makes expected calls', () => {
spyOn(component, 'getDateFormat').and.callThrough();
spyOn(component, 'CalculateAge').and.callThrough();
spyOn(apollo, 'query').and.callThrough();
component.getAllStudents();
expect(apollo.query).toHaveBeenCalled();
expect(component.getDateFormat).toHaveBeenCalled();
expect(component.CalculateAge).toHaveBeenCalled();
});
});
给了我一个错误。 “预计间谍getDateFormat被称为。”有人可以指导我解决这个问题吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
getallstudents
包括异步代码。使用observable.subscribe
,您的代码将收到有关可用结果
的延迟通知,很可能在期望
已评估后。存在使用
Jasmine
测试异步代码的不同方法(请参阅摘自茉莉花文档)。Angular
还提供了测试异步代码的功能。例如,您可以在tick()
调用getAllstudents()
。这看起来如下:The problem is that
getAllStudents
includes asynchronous code. WithObservable.subscribe
, your code will receive a delayed notification of the availableresult
, most probably afterexpect
has been evaluated.There exist different ways to test asynchronous code with
Jasmine
(see Asynchronous Work from Jasmine documentation).Angular
also provides functionality to test asynchronous code. You can for example execute your unit test in thefakeAsync
zone. Then, you need to invoketick()
just after callinggetAllStudents()
. This could look as follows: