如何使用茉莉花中的间谍

时间:2018-08-28 05:34:37

标签: angular jasmine karma-jasmine

我对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

中突出显示了条件,

请让我知道我在这里做错了。

1 个答案:

答案 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,因此您可以在此处查看。