我对Angular和茉莉花很陌生,在做模拟游戏时遇到了问题:
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
请让我知道我在这里做错了。
答案 0 :(得分:1)
我为uploadFile
方法创建了简单的单元测试:该测试期望当我们有非空的modalService.open
数组时,将使用模拟的参数调用filePath
:
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
,因此我们必须模拟该注入器,为此我们可以创建jasmine spy object:
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语句,因此如果modalService.open
数组为空,则不会调用filePath
方法。这正是我们在上一个示例中所期望的。
还创建了一个stackblitz demo,因此您可以在此处查看。