如何对 angular 中创建导入对象 class 的方法进行单元测试

How to unit test a method in angular which creates object of imported class

我正在使用 jasmine 和 karma 对 angular 组件进行单元测试。 Comonent 有一个方法可以创建导入的 class 的新对象并调用其成员函数之一。我应该如何为以下场景编写单元测试用例。

myapp.component.ts

的相关代码
import { pdfctrls } from '../path/to/pdfctrl';

@Component({
  selector: 'app-myapp',
  templateUrl: './myapp.component.html',
  styleUrls: ['./myapp.component.css']
})
export class MyappComponent {
  obj: any;

  // other variables and method 

  // this method needs to be unit tested
  downloadPdf() {
    const pdf: pdfctrls = new pdfctrls(this.obj);
    pdf.getPdfData('filename');
  }

  // rest of the methods
}

pdfctrl.ts

的相关代码
export class pdfctrls {
  obj: any;

  constructor(obj) {
    this.obj= obj;
  }

  getPdfData = function (params) {
    // method implementation
  }

  // rest of the methods

我曾尝试监视 pdfctrl class 但没有成功。首选 myapp.component.ts 中更改最少的解决方案。

好的,所以有两种方法:

  1. 您更改代码并注入服务 PdfCtrls ,这将帮助您模拟 。正如@Alan 所建议的,这是模拟的唯一方法。

  2. 或者作为您所要求的“最少变化”的解决方法,您可以这样做:

import { pdfctrls } from '../path/to/pdfctrl';

@Component({
  selector: 'app-myapp',
  templateUrl: './myapp.component.html',
  styleUrls: ['./myapp.component.css']
})
export class MyappComponent {
  obj: any;
  pdf: pdfctrls; // <------- CREATE IT AT COMPONENT LEVEL
  // other variables and method 

  // this method needs to be unit tested
  downloadPdf() {
    this.pdf = new pdfctrls(this.obj);
    this.pdf.getPdfData('filename');
  }

  // rest of the methods
}

spec.ts

  it('should create pdf object on downloadPDF()', () => {
    expect(component.pdf).toBeUndefined();
    component.downloadPDF();
    expect(component.pdf).toBeDefined();
    expect(component.pdf).toEqual(jasmine.objectContaining({
      someproperties: "someproperties"
    }));
  });

通过此测试,您可以确保对象已正确创建。您无法测试 getPDFData() 是否被调用或现在被调用。