我有个问题。我有一个函数使用异步等待来获取数据,但现在我正在尝试测试它。我不知道如何做到这一点。我试过这个这是我的组件
async loadTodos() {
try {
const todosData = await this.testService.loadTodos();
this.todos = todosData;
console.log('posts', todosData);
} catch (error) {
console.log(error);
}
}
这是我的服务文件
export class TestService {
constructor(private readonly http: HttpClient) {}
async loadTodos(): Promise<any[]> {
return this.http
.get<any[]>('https://jsonplaceholder.typicode.com/todos')
.toPromise();
}
}
最后这是我的测试
it('test', () => {
const response2 = [
{
userId: 1,
id: 1,
title: 'delectus aut autem',
completed: false,
},
{
userId: 1,
id: 2,
title: 'quis ut nam facilis et officia qui',
completed: false,
},
];
testServiceSpy.loadTodos.and.returnValue(of(response2).toPromise());
component.loadTodos();
expect(component.todos).toEqual(response2);
});
我在sintax中没有错误,但在终端中我看到了这个。
TypeError: Cannot read properties of undefined (reading 'loadTodos')
这表示testServiceSpy
为空。你可以做的是检查你是否将其设置为beforeEach或做类似的事情。您还需要使测试本身异步,并等待对组件的调用。
it('test', async () => {
// grab the instance of the TestService
const serviceSpy = TestBed.inject(TestService) as jasmine.SpyObj<TestService>;
const response2 = [
{
userId: 1,
id: 1,
title: 'delectus aut autem',
completed: false,
},
{
userId: 1,
id: 2,
title: 'quis ut nam facilis et officia qui',
completed: false,
},
];
serviceSpy.loadTodos.and.returnValue(of(response2).toPromise());
// await the call to the component
await component.loadTodos();
expect(component.todos).toEqual(response2);
});