【发布时间】: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