【问题标题】:How to unit test a method in angular which creates object of imported class如何对创建导入类对象的角度方法进行单元测试
【发布时间】:2020-05-21 09:11:10
【问题描述】:

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

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 类,但没有成功。首选对myapp.component.ts 进行最少更改的解决方案。

【问题讨论】:

  • 您不能监视在您的 main 方法中实例化的对象。为此,您必须通过依赖项注入该对象。然后,您可以使用模拟声明提供程序。
  • @Alan 我现在无法更改代码。有什么办法可以测试这段代码吗?
  • @MohitKhandelwal 如果有帮助,请将其标记为答案。它会帮助其他也在寻找类似问题的人

标签: angular typescript unit-testing jasmine karma-jasmine


【解决方案1】:

好的,有两种方法:

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

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

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() 或现在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2021-03-11
    • 2011-10-21
    • 2019-09-08
    相关资源
    最近更新 更多