0

我有以下服务:

@Injectable({
  providedIn: 'root'
})
export class Service1 {
  dataHasChanged = new Subject();
  private data1;
  private data2;

  constructor() {}
  
  getData() {
    return {
      data1: this.data1,
      data2: this.data2
    }
  }

  setData(data1, data2) {
    this.data1 = data1;
    this.data2 = data2;
    this.dataHasChanged.next({
      data1: this.data1,
      data2: this.data2;
    })
  }
}
@Injectable({
  providedIn: 'root'
})
export class Service2 {
  constructor(private service1: Service1) {}

  fetchClient(): Observable<ITest> {
    const data = service1.getData();
    return this.http.post(
      '/api-endpoint/123',
       {
         data: data
        }
     );
  }

  reload(): Observable<ITest> {
    return this.service1.dataHasChanged.pipe(
      mergeMap(() => this.fetchClient()),
    );
  }
}


我想测试每次触发 dataHasChanged 时,一个具有 的组件service2.reload()从其订阅中接收数据。

我为它创建了以下测试:

describe('Service2', () => {
  let service2: Service2;
  let httpMock: HttpTestingController;
  let service1: Service1;
  let service1Stub: Partial<Service1>;

  beforeEach(() => {
    service1Stub = {
      dataHasChanged: new Subject(),
      getData: function () {
        return {
          data1: 123,
          data2: 12345
        }
      }
    };
    
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        Service2,
        {
          provide: Service1,
          useValue: Service1Stub
        }
      ]
    });

    service2 = TestBed.inject(service2);
    httpMock = TestBed.inject(HttpTestingController);
    service1 = TestBed.inject(service1);
  });

it('test', (done: DoneFn) => {  
    service2.reload().subscribe((data) => {
      console.log('here')
      expect(data).toBeDefined();
      done();
    });

    service1.dataHasChanged.next()
  })
});

问题是订阅回调中的测试永远不会执行......编写该测试的正确方法是什么?

4

1 回答 1

0

我发现我忘记模拟具有 http 方法的 fetchClient 方法。

这有效:

it('test', (done: DoneFn) => {  
    spyOn(service2, 'fetchData').and.returnValue(of{
        data1: 123,
        data2: 123
    })

    service2.reload().subscribe((data) => {
      console.log('here')
      expect(data).toBeDefined();
      done();
    });

    service1.dataHasChanged.next()
  })
于 2022-02-11T22:30:14.013 回答