0

我看到了如何在 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 提供的此类服务?
  • 如果我想使用这种方法,我应该将它作为一项基本服务进行测试?

我等你的答案

4

2 回答 2

0

我能够使用这种方法在提供程序中模拟服务(不使用 AppolloTestingModule)来使其工作。制作了一个辅助函数graphQlServiceMock,以便在所有服务中重用。

TestBed.configureTestingModule({
  ...
  providers: [
    {
       provide: MyGQLService,
       useValue: graphQlServiceMock({ users: null }),
    },
  ]

})
export const graphQlServiceMock = (response: any) => ({
  watch: () => ({
    valueChanges: of({
      data: {
        ...response,
      },
      loading: false,
    }),
  }),
});

或没有帮手..

TestBed.configureTestingModule({
  ...
  providers: [
  {
    provide: MyGQLService,
    useValue: {
      watch: () => ({
        valueChanges: of({
          data: {
            users: null,
          },
          loading: false,
        }),
      }),
    },
  },
 ];
})
于 2022-01-21T17:20:37.320 回答
0

尝试实例化你的服务并用methode countryService.watch() then调用它

countryService.watch().valueChanges.subscribe(console.log);
于 2020-05-15T05:14:26.113 回答