我正在使用jasmine和karma对一个angular组件进行单元测试。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
是首选。
好吧,那么有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()
被称为或现。