我看到了如何在 Angular 中测试 apollo的示例,并且基本上只使用ApolloTestingModule进行测试。我的测试看起来像:
测试服
describe('CountriesService', () => {
let countryService: CountriesService;
let controller: ApolloTestingController;
let scheduler: TestScheduler;
let countries: any;
beforeAll(() => {
TestBed.configureTestingModule({
imports: [ApolloTestingModule],
});
countries = [{ code: 'C1', phone: '500', name: 'Country' }];
scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
countryService = TestBed.inject(CountriesService);
controller = TestBed.inject(ApolloTestingController);
});
test('should be created', () => {
expect(countryService).toBeTruthy();
});
test('should return an array of countries', () => {
countryService.watch().valueChanges.subscribe(console.log);
const operation = controller.expectOne(COUNTRIES_GQL);
operation.flush({ data: { countries } });
controller.verify();
});
});
服务
@Injectable({ providedIn: 'root' })
export class CountriesService {
constructor(private apollo: Apollo) {}
watch() {
return this.apollo.watchQuery({
query: COUNTRIES_GQL,
});
}
}
问题
我想使用使用 查询、变异、订阅服务的方法,但是使用这种方法测试不起作用。
@Injectable({ providedIn: 'root' })
export class CountriesService extends Query<any> {
document = COUNTRIES_GQL;
}
错误
● CountriesService › should return an array of countries
TypeError: Cannot read property 'use' of undefined
30 |
31 | test('should return an array of countries', () => {
32 | countryService.watch().valueChanges.subscribe(console.log);
| ^
33 |
34 | const operation = controller.expectOne(COUNTRIES_GQL);
35 | operation.flush({ data: { countries } });
对我来说,这个错误是有道理的,因为在Query 类的官方实现中,方法 fetch 和 watch 使用的是 Apollo 服务提供的use 方法。
问题
- 是否可以替代测试 apollo 提供的此类服务?
- 如果我想使用这种方法,我应该将它作为一项基本服务进行测试?
我等你的答案