gpt4 book ai didi

Angular 服务测试 : Cannot find name 'asyncData'

转载 作者:太空狗 更新时间:2023-10-29 17:01:56 24 4
gpt4 key购买 nike

所以我正在学习如何在 Angular 中测试服务,并尝试在 Angular 文档中复制以下示例。

let httpClientSpy: { get: jasmine.Spy };
let heroService: HeroService;

beforeEach(() => {
// TODO: spy on other methods too
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
heroService = new HeroService(<any> httpClientSpy);
});

it('should return expected heroes (HttpClient called once)', () => {
const expectedHeroes: Hero[] =
[{ id: 1, name: 'A' }, { id: 2, name: 'B' }];

httpClientSpy.get.and.returnValue(asyncData(expectedHeroes));

heroService.getHeroes().subscribe(
heroes => expect(heroes).toEqual(expectedHeroes, 'expected heroes'),
fail
);
expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
});

我试图按字面意思复制它,但它给了我以下错误:

ERROR in src/app/services/find-locals.service.spec.ts(17,38): error TS2304: Cannot find name 'asyncData'.

有人可以帮我替换这个吗?或者告诉我我可能在其他地方做错了什么?

这是从 Angular 文档复制的测试文件:

import {FindLocalsService} from './find-locals.service';

import {HttpClient, HttpClientModule} from '@angular/common/http';

let findLocalsService: FindLocalsService;
let httpClientSpy: { get: jasmine.Spy, post: jasmine.Spy };

beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'post']);
findLocalsService = new FindLocalsService(<any> httpClientSpy, null);
});

it('should save location to server', function () {
const expectedData: any =
[{ id: 1, name: 'A' }, { id: 2, name: 'B' }];

httpClientSpy.post.and.returnValue(asyncData(expectedData));

findLocalsService.saveLocation('something').subscribe(
data => expect(data).toEqual(expectedData),
fail
);

expect(httpClientSpy.post.calls.count()).toBe(1, 'one call');
});

这是服务本身

@Injectable()

export class FindLocalsService {

constructor(private http: HttpClient, private authService: AuthenticationService){}

saveLocation(locationObj){
return this.http.post(url + '/findLocals/saveLocation', locationObj);
}

getThreeClosestPlayers() {
const userId = this.authService.currentUser().user._id;
console.log('entered 3 closest service', userId);

return this.http.get(url + '/findLocals/getThreeClosestPlayers/' + userId)
.pipe(
map((data: any) => data.obj),
catchError(this.handleError)
)
}
}

最佳答案

改变这一行:

httpClientSpy.get.and.returnValue(asyncData(expectedHeroes));

使用 Observable 运算符 of()

httpClientSpy.get.and.returnValue(of(expectedHeroes));

这将返回一个可以订阅的可观察对象,并将返回 expectedHeroes。如果您使用的是 Angular 6,则可以直接从 rxjs 导入:

import {of} from 'rxjs';

关于 Angular 服务测试 : Cannot find name 'asyncData' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52283055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com