角度 |类型为"User[]"的参数不能分配给类型为"预期"的参数<User>



在测试过程中,我得到了这个错误,我不知道它是从哪里来的。

错误与toBe()

中的用户有关。user.service.spec.ts

it('should call getUsersById', () => {
const user: User [] = [
{
"id": 23556,
"name": "unique Ramakrishna",
"email": "new.ramakrishna@15ce.com",
"gender": "male",
"status": "active"
}
]
userService.APIkey = '89668b2e3000a3aab5860410aa59fdc6c98977afa03a15d19df6be0e22f91650'
let APIkey = userService.APIkey
let url = 'https://gorest.co.in/public/v2/users'
let nUsers = '10';
let nPage = 1;
let id = 23556
userService.getUserById(id).subscribe((res) => {
expect(res).toBe(user) // ERROR:The argument of type 'User[]' cannot be assigned to the parameter of type 'Expected<User>'.
});
const req = httpTestingController.expectOne({
method: 'GET',
url: `${url}/${id}?access-token=${APIkey}`,
});
req.flush(user);
});

user.service.ts这是我从服务

发出的GET by ID调用
/** GET user by id(DETAIL) */
getUserById(id: number): Observable<User> {
const url = `${this.url}/${id}?access-token=${this.APIkey}`;
return this.http.get<User>(url).pipe(
tap(_ => this.log(`fetched user id=${id}`)),
catchError(this.handleError<User>(`getUser id=${id}`))
);
}

User.ts

export interface User {
id: number;
name: string;
email: string;
gender: string;
status: string;
}

我在网上搜索,但没有找到任何解决方案。有人能帮我吗?

你得到这个错误,因为在你的代码res是一个UseruserUser的数组。你可以取数组的第一个元素:expect(res).toBe(user[0]),或者(可能更合适)重构你的代码,使user是一个对象而不是数组:

const user: User = {
"id": 23556,
"name": "unique Ramakrishna",
"email": "new.ramakrishna@15ce.com",
"gender": "male",
"status": "active"
}

最新更新