簡體   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