【问题标题】:Why Spy is not called in the Mock (Angular 4)为什么在 Mock 中不调用 Spy(Angular 4)
【发布时间】:2018-03-13 01:57:29
【问题描述】:

您能否检查下面的测试,看看为什么间谍永远不会被调用?实际代码运行良好,但测试没有播放。

如果我在this.apiSrv.fetch 内有spyOn 的东西,那么测试通过了。很奇怪!

提前谢谢你。

manager.service.spec.ts

describe('ManagerService', () => {
    
  const mockClass = new MockClass();
  let spy;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        ManagerService,
        { provide: ApiService, useValue: mockClass},
      ]
    });
    spy = spyOn(mockClass, 'fetch');
  });

    fit('should call server', inject([ManagerService], (service: ManagerService) => {
      service.callServer();
      expect(spy).toHaveBeenCalled();
    }));
    
});

manager.service.ts

@Injectable()
export class ManagerService {
  constructor(
    private apiSrv: ApiService,
  ) {}

  public callServer() {
    this.apiSrv.fetch('http://url.com').subscribe( (data) => {
       console.log(data);
    });
  }
}

api.service.ts

export class ApiService {
    
  constructor(private http: Http) {}
    
  fetch(resource: string) {
      return this.http.get(resource).map((response) => response.json());
  }
}

模拟.ts

export class MockClass {
    public fetch(): Observable<any> {
        const expectedResult = {
            items: {
                data: [],
            }
        };
        return Observable.of(expectedResult);
    }
}

结果:

【问题讨论】:

    标签: angular unit-testing jasmine mocking observable


    【解决方案1】:

    您需要确保MockClass.fetch 方法实际上被调用(而不仅仅是存根),因为您将它与.subscribe 方法链接起来,否则会导致错误并且无法通过测试。所以应该使用callThrough

    spy = spyOn(mockClass, 'fetch').and.callThrough();
                                   ^^^^^^^^^^^^^^^^^^ 
                                       add this
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2014-09-15
      • 2020-09-07
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      相关资源
      最近更新 更多