I saw the examples of how testing apollo in angular works and basically only use the ApolloTestingModule to make the tests. And my test looks like:
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,
});
}
}
I want to use the approach of using Query, Mutation, Subscription service but with this approach the test doesn't work.
@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 } });
For me the error makes sense because in the official implementation of Query class the methods fetch and watch are using the use method provided by Apollo service.
I wait for your answers
try to instance ur service and call it with the methode countryService.watch()
then
countryService.watch().valueChanges.subscribe(console.log);
I was able to get it working using this approach mocking the service in providers (does not use AppolloTestingModule). Made a helper function graphQlServiceMock
for reuse across all services.
TestBed.configureTestingModule({
...
providers: [
{
provide: MyGQLService,
useValue: graphQlServiceMock({ users: null }),
},
]
})
export const graphQlServiceMock = (response: any) => ({
watch: () => ({
valueChanges: of({
data: {
...response,
},
loading: false,
}),
}),
});
or without helper..
TestBed.configureTestingModule({
...
providers: [
{
provide: MyGQLService,
useValue: {
watch: () => ({
valueChanges: of({
data: {
users: null,
},
loading: false,
}),
}),
},
},
];
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.