Итак, я учусь тестировать сервисы в Angular и попытался скопировать приведенный ниже пример в Angular docs.
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');
});
Я попытался скопировать его буквально, но выдает следующую ошибку:
ОШИБКА в src / app / services / find-locals.service.spec.ts (17,38): ошибка
TS2304: не удается найти имя '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)
)
}
}