【问题标题】:Test angular http service with jest用 jest 测试 Angular http 服务
【发布时间】:2022-06-10 21:22:25
【问题描述】:

我想测试是否在 http 服务层中调用了我的辅助函数之一,但测试失败。我是开玩笑的新手,所以请告诉我我做错了什么

服务层

public customerUpload(
    file: Blob,
    name?: string): Observable<CustomerResponse> {
    
    if (name!== '') {
      parameters = addQueryPara(name, 'name');
    }

return this.http.post(file, parameters)
)

我想检查我是否使用名称调用了 CustomerUpload,它应该调用 addQueryPara

我的规格文件测试


import * as helper from 'app/shared/helper.ts';


describe('customerService', () => {
  let service: customerService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
    });
    service = TestBed.inject(customerService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });


describe('when customer is called', () => {
  beforeEach(() => {
    const response = getMockResponse();
    jest.spyOn(service, 'customerUpload').mockReturnValue(of(response) as any);
  });

  it('should add http params', () => {
    service.customerUpload(new Blob(), 'learn');
    expect(jest.spyOn(helper, 'addQueryPara')).toHaveBeenCalledTimes(1); // This is failing
  });
});

});

addQueryPara 失败。如何确定我是否传递了一个参数,它调用了 addQueryPara?

【问题讨论】:

    标签: angular unit-testing testing jestjs


    【解决方案1】:

    我不知道jest,但我认为当您使用jest.spyOn(...).mockReturnValue(...) 时,您正在使用mockReturnValue 存根方法并丢失实现细节。

    另一件事是,您在调用该方法之后进行间谍活动,但您应该在之前进行间谍活动。

    我会首先使用HttpClientTestingModule 而不是真正的HttpClientModule 进行测试,因此不会发送实际的 API 调用,您可以断言发送了哪些 API 调用。

    尝试删除mockReturnValue,看看是否通过。

    import * as helper from 'app/shared/helper.ts';
    
    
    describe('customerService', () => {
      let service: customerService;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          // !! Change to HttpClientTestingModule
          imports: [HttpClientTestingModule],
        });
        service = TestBed.inject(customerService);
      });
    
      it('should be created', () => {
        expect(service).toBeTruthy();
      });
    
    
    describe('when customer is called', () => {
      beforeEach(() => {
        const response = getMockResponse();
        !! remove mockReturnValue
        jest.spyOn(service, 'customerUpload');
      });
    
      it('should add http params', () => {
        // !! move this up before calling the method so we are actually spying before
        const addSpy = jest.spyOn(helper, 'addQueryPara');
        service.customerUpload(new Blob(), 'learn');
        // !! assert now
        expect(addSpy).toHaveBeenCalledTimes(1);
      });
    });
    
    });
    

    查看此链接以使用 HTTP 测试服务:https://testing-angular.com/testing-services/#testing-a-service-that-sends-http-requests

    它使用 Karma 和 Jasmine 而不是 Jest,但想法是一样的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 2018-12-11
      • 2017-11-23
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      相关资源
      最近更新 更多