【问题标题】:How to write a unit test for an async method?如何为异步方法编写单元测试?
【发布时间】:2020-02-03 15:23:07
【问题描述】:

我有以下测试代码:

import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {inject, TestBed} from '@angular/core/testing';
import {AviorBackendService} from './avior-backend.service';

describe('AviorBackendService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [AviorBackendService],
  }));

  it('should be created', () => {
    const service: AviorBackendService = TestBed.get(AviorBackendService);
    expect(service).toBeTruthy();
  });

  // Inject the `done` method. This will tell the test suite that asynchronous methods are being called
  // and it will mark the test as failed if within a specific timeout (usually 5s) the `done` is not called
  it('expects service to fetch data with proper sorting', (done) => {
    const service: AviorBackendService = TestBed.get(AviorBackendService);
    // tslint:disable-next-line: prefer-const
    let httpMock: HttpTestingController;
    service.getUserCollection().subscribe(data => {
      expect(data.length).toBe(7);
      const req = httpMock.expectOne('http://localhost:3000/users');
      expect(req.request.method).toEqual('GET');      // Then we set the fake data to be returned by the mock
      req.flush({firstname: 'Chad'});
      done(); // Mark the test as done
    }, done.fail); // Mark the test as failed if something goes wrong
  });
});

我需要为提供的函数编写一个原型测试(然后我将为其他类似函数编写其余部分)。我仍在学习如何编写测试,据我所知,我需要使用模拟,但我不明白如何。 我要测试的代码是:

  getUserCollection() {
    // withCredentials is very important as it passes the JWT cookie needed to authenticate
    return this.client.get<User[]>(SERVICE_URL + 'users', { withCredentials: true });
  }

我的测试代码报错Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

更新

我的 user-collection.model.ts:

import { User } from './user.model';

export interface UserCollection {

    user: User[];

}

我的 user.model.ts:

import { Role } from './role';

// was class and not interface!
export interface User {
    _id: number;
    mandator?: number;
    loginId: string;
    lastname: string;
    firstname: string;
    password: string;
    eMail: string;
    group?: string;
    role?: Role;
    active?: boolean;
    token?: string;
}

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

    您在错误的位置(永远不会被遍历的地方)执行flush

    尝试以下方法:

    describe('AviorBackendService', () => {
      let httpTestingController: HttpTestingController;
      let service: AviorBackendService;
    
      beforeEach(() => {
       TestBed.configureTestingModule({
         imports: [HttpClientTestingModule],
         providers: [AviorBackendService],
       });
    
       httpTestingController = TestBed.get(HttpTestingController);
       service = TestBed.get(AviorBackendService);
      });
    
      it('should be created', () => {
        expect(service).toBeTruthy();
      });
    
      it('expects the service to fetch data with proper sorting', () => {
        const mockReponse = { firstName: 'Chad' };
    
        service.getUserCollection().subscribe(data => {
          expect(data.firstName).toEqual('Chad');
        });
        const req = httpTestingController.expectOne('IN HERE PUT WHATEVER SERVICE_URL + 'users' EQUALS TO');
        expect(req.request.method).toEqual('POST');
        // send the response to the subscribe.
        req.flush(mockResponse);
      });
    });
    

    关于如何在 Angular 中测试 HTTP 服务的好链接 (https://medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf)

    【讨论】:

    • 我得到Error: Expected one matching request for criteria "Match URL: localhost:3000/users", found none. 并且在service.getUserCollection().subscribe(data =&gt; { expect(data.firstname).toEqual('Namehere'); }); 部分它抛出Property 'firstname' does not exist on type 'User[]'....
    • 是的,因为它不是localhost:3000/usersSERVICE_URL 是什么?不要输入localhost:3000/users,而是输入SERVICE_URL/users,但您必须弄清楚SERVICE_URL 的实际值是什么并使用它。另一个问题是,在您的服务中有&lt;User[]&gt;,那么它会返回一组用户吗?如果是这样,请const mockResponse = [{ firstName: 'Chad' }];
    • SERVICE_URL 是 localhost:3000。是的,就是这样。
    • 试试const mockResponse = [{ firstName: 'Chad' } as User];。对于SERVICE_URLlocalhost,看是不是https://localhost:3000。而且,在it 测试的开头,console.log(service.SERVICE_URL)。如果SERVICE_URL 未公开,则仅公开此console.log 以查看其实际值。
    • 通过输入 as User 我得到 Conversion of type '{ firstName: string; }' to type 'User' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ firstName: string; }' is missing the following properties from type 'User': _id, loginId, lastname, firstname, and 2 more. 不,它是 http:// 而不是 https://。如果我输入console.log 我会得到Property 'SERVICE_URL' does not exist on type 'AviorBackendService'. 并得到Property 'firstName' does not exist on type 'User[]'.如何将SERVICE_URL 公开?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多