![](/img/trans.png)
[英]Angular Unit Testing - How to test a service which creates a Websocket
[英]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
進行最少更改的解決方案。
好的,所以有兩種方法:
您更改代碼並注入服務PdfCtrls
,這將幫助您進行模擬。 正如@Alan 所建議的,這是模擬的唯一方法。
或者作為您要求的“最小變化”的解決方法,您可以這樣做:
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.