【问题标题】:Angular unit test cases service methodAngular 单元测试用例服务方法
【发布时间】:2021-04-06 13:19:25
【问题描述】:

问题:当我为服务文件运行单元测试用例时,它会说

'Spec 'MerchantsService getMerchantData' 没有任何期望。' 请帮忙,而不是显示 console.log。提前致谢。

下面是我的服务文件包含的内容

  getMerchantData(searchParams: any): Observable<any> {
    return this.http.get(`${this.baseUrl}/merchants-data-url${searchParams}`)
  }

以下是服务的规范文件。

import { async, inject, TestBed } from '@angular/core/testing'
import { MerchantsService } from './merchants.service'
import { HttpClientTestingModule } from '@angular/common/http/testing'
import { ReactiveFormsModule, FormsModule } from '@angular/forms'

describe('MerchantsService', () => {
  let service: MerchantsService

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, ReactiveFormsModule, FormsModule],
    })
    service = TestBed.inject(MerchantsService)
  })

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

  it('getMerchantData', async() => {
    service.getMerchantData('?page=1').subscribe((res) => {
      console.log('getMerchantData', res.data)
      expect(res.data.length).toBeGreaterThan(0)
    })
  })
})

【问题讨论】:

    标签: javascript angular unit-testing karma-jasmine


    【解决方案1】:

    您需要测试 http 调用并做出模拟响应。

    试试这个:

    import { async, inject, TestBed } from '@angular/core/testing'
    import { MerchantsService } from './merchants.service'
    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'
    import { ReactiveFormsModule, FormsModule } from '@angular/forms'
    
    describe('MerchantsService', () => {
      let service: MerchantsService;
      let httpTestingController: HttpTestingController;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [HttpClientTestingModule, ReactiveFormsModule, FormsModule],
        })
        service = TestBed.inject(MerchantsService);
        httpTestingController = TestBed.inject(HttpTestingController);
      });
    
      afterEach(() => {
        // after each test, verify no outstanding api calls remain
        httpTestingController.verify();
      });
    
      it('should be created', () => {
        expect(service).toBeTruthy();
      });
    
      it('getMerchantData', () => {
        const mockMerchantData = {
          data: [{ id: 1 }, { id: 2 }], // mock your response to whatever you want
        };
        service.getMerchantData('?page=1').subscribe((res) => {
          console.log('getMerchantData', res.data)
          expect(res.data.length).toBeGreaterThan(0)
        });
        // you have to know your Base URL and put it in the placeholder below
        const req = httpTestingController.expectOne(`${BASE_URL_HERE}/merchants-data-url?page=1`);
        expect(req.request.method).toEqual('GET'); // expect a get request
        req.flush(mockMerchantData); // give this response to the API call in queue
      });
    })
    

    您应该阅读this 文章,了解如何在 Angular 中测试 HTTP 调用。

    【讨论】:

      【解决方案2】:

      我认为这是因为您的方法“getMerchantData”在任何期望完成之前就完成了。您的订阅回调不会在方法结束时执行。

      你应该这样尝试:

      it('getMerchantData', (done) => {
          service.getMerchantData('?page=1').subscribe((res) => {
             console.log('getMerchantData', res.data)
             expect(res.data.length).toBeGreaterThan(0)
             done()
          })
      })
      

      顺便说一句,你会有另一个问题,你应该像 AliF50 在他的回复中所说的那样模拟 http 响应:https://stackoverflow.com/a/66970121/4923347

      您应该阅读如何测试异步测试:

      【讨论】:

        猜你喜欢
        • 2019-05-06
        • 1970-01-01
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 2014-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多