我正在使用茉莉花和业力对角组件进行单元测试。 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
中进行最少更改的解决方案。
答案 0 :(得分:2)
好,所以有两种方法:
您更改代码并注入服务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"
}));
});
通过此测试,您可以确保已正确创建对象。您无法测试是否调用了getPDFData()
或现在。