如何为异步方法编写单元测试? [英] How to write a unit test for an async method?

查看:224
本文介绍了如何为异步方法编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下测试代码:

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
  });
});

我需要为提供的功能编写一个原型测试(然后,其余的将为其他类似的功能编写).我仍在学习如何编写测试,据我所知,我需要使用模拟程序,但我不知道如何使用. 我要测试的代码是:

I need to write a prototype test for the supplied function (then I'll write the rest for the other similar functions). I am still learning how to write tests and as far I as I understand I need to use a mock, but I don't understand how. My code to test is:

  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.

My test code gives out an error Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

更新

我的user-collection.model.ts:

My user-collection.model.ts:

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

export interface UserCollection {

    user: User[];

}

我的user.model.ts:

My 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;
}

推荐答案

您在错误的位置(永远不会被穿越的位置)上执行flush.

You're doing the flush in a wrong location (a place that will never be traversed).

请尝试以下操作:

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 )

A good link on how to test HTTP Service in Angular (https://medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf)

这篇关于如何为异步方法编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆