繁体   English   中英

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

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

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

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

通过此测试,您只需确保已正确创建 object。 您无法测试是否调用了getPDFData()或现在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM