我对 Angular 和 jasmine 很陌生,我在做模拟时遇到了问题:
public uploadFile(confirm) {
this.uploadModalRef.close();
if (this.filePath.length) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : 'false',
windowClass: 'custom-class'
};
this.importModalRef = this.modalservice.open(confirm, ngbModalOption);
}
}
这是我正在尝试的:
it('should upload the file', () => {
let close: "11";
let filepath;
component.uploadFile;
expect(component.uploadFile([filePath]) = ['11'].toBe(close);
});
但是,如果在代码覆盖率和this.uploadModalref
中突出显示条件
请让我知道我在这里做错了什么。
我已经为uploadFile
方法创建了简单的单元测试:该测试期望当我们有非空filePath
数组时,将使用模拟参数调用modalService.open
:
describe('HelloComponent', () => {
let fixture: ComponentFixture<TestComponent>;
let component: HelloComponent;
const modalService: NgbModal = jasmine.createSpyObj('modalService', ['open']);
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ HelloComponent, TestComponent ],
providers: [{
provide: NgbModal,
useValue: modalService
}]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.debugElement.children[0].componentInstance;
fixture.detectChanges();
});
it('should call modalService.open on uploadFile', () => {
component.filePath = 'File1';
component.uploadModalRef = jasmine.createSpyObj('uploadModalRef', ['close']);
let mockOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false,
windowClass: 'custom-class'
};
const mockConfirm = 'confirm-template';
component.uploadFile(mockConfirm);
expect(modalService.open).toHaveBeenCalledWith(mockConfirm, mockOptions);
});
});
由于您的组件取决于NgbModal
因此我们必须模拟此注入器,为此我们可以创建茉莉花间谍对象:
const modalService: NgbModal = jasmine.createSpyObj('modalService', ['open']);
然后,我们使用我们创建的间谍对象向测试模块提供程序提供NgbModal
。这将使我们能够监视它的方法(在本例中,它是open
方法(。
在测试本身中,我们遵循AAA模式:安排行为断言。首先,我们通过创建模拟数据来排列类属性和方法参数。然后我们将目标函数调用uploadFile
。最后 - 我们期望modalService.open
方法将使用正确的参数调用。您还可以通过更改模拟数据来添加基于此示例的另一个单元测试。例如:
it('should not call modalService.open on uploadFile when filePath is empty', () => {
component.filePath = '';
component.uploadModalRef = jasmine.createSpyObj('uploadModalRef', ['close']);
const mockConfirm = 'confirm-template';
component.uploadFile(mockConfirm);
expect(modalService.open).not.toHaveBeenCalled();
});
由于uploadFile
方法中存在 if 语句,因此如果filePath
数组为空,则不会调用modalService.open
方法。这正是我们在上一个示例中所期望的。
还创建了一个堆栈闪电战演示,所以你可以在这里查看。