是否可以在Angular组件中验证服务调用?

时间:2018-10-09 13:53:26

标签: angular unit-testing jasmine karma-jasmine

我在尝试验证Angular 5组件函数中的服务调用时遇到许多问题。

@Component({
    selector: 'app-example',
    templateUrl: './app-example.html',
    styleUrls: ['./app-example.css'],
    providers: [ PersistanceService, AnotherService ]
})
export class ExampleComponent {

    callPersist: boolean = false;

    private simpleObj = {
        "name": "a",
        "age" : 20
    }

    constructor(private persistanceService: PersistanceService, anotherService: AnotherService) {}

    persist() {
        if (this.callPersist)
            this.persistanceService.persist(this.simpleObj);
        else
            this.anotherService.terminate();
    }
}

在测试中,我想验证是否在调用 persist()后调用了相应的服务。这是我的测试用例:

it('should call persistService', () => {

    let persistService = TestBed.get(PersistanceService); //this is being declared in TestBed.configureTestingModule

    spyOn(persistService, 'persist').and.callThrough(); //create spy

    component.callPersist = true; //set flag for persistance
    fixture.detectChanges(); //update variables in fixture

    component.persist(); //call parent method

    expect(persistService.persist).toHaveBeenCalled(); // error
    expect(persistService).toHaveBeenCalled(); // error
    expect(persistService.calls.any()).toBeTruthy(); //error
});

无论期望如何,结果始终是

  

预期的间谍仍然被召唤。

满足期望的唯一情况是当我直接在测试用例内部调用间谍时。但是,这对我没有用。我希望使用 .verify();

像Mockito一样验证我的服务调用

我对此有完全错误的机会吗?

PS:测试是通过Jasmine 2.8.0进行的

编辑:添加beforeEach()方法

beforeEach(async() => {
    TestBed.configureTestingModule({
        declarations: [ ExampleComponent ],
        providers: [
            PersistanceService,
            AnotherService
        ]
    }).compileComponents();

    fixture = TestBed.createComponent(ExampleComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
});

1 个答案:

答案 0 :(得分:4)

让我们看看您要测试什么。

您拥有在组件级别提供服务的组件:

@Component({
    ...
    providers: [ PersistanceService, AnotherService ]
})
export class ExampleComponent {

然后在您的测试中,您将在根模块级别上提供相同的服务:

TestBed.configureTestingModule({
    declarations: [ ExampleComponent ],
    providers: [
        PersistanceService,
        AnotherService
    ]
}).compileComponents();

您可以猜测,运行测试时,这些服务将是完全不同的实例。

如何检查?

const componentPersistService = fixture.debugElement.injector.get(PersistanceService);
const globalPersistService = TestBed.get(PersistanceService);

componentPersistService === globalPersistService // false

另请参阅文档:

我认为您现在了解我们需要测试组件级别提供的服务。

您在这里:

it('should call persistService', () => {
   const persistService = fixture.debugElement.injector.get(PersistanceService);

   const persistSpy = spyOn(persistService, 'persist').and.callThrough(); // create spy

   component.callPersist = true; // set flag for persistance
   fixture.detectChanges(); // update variables in fixture

   component.persist(); // call parent method

   expect(persistService.persist).toHaveBeenCalled(); // error
   expect(persistSpy).toHaveBeenCalled(); // error
   expect(persistSpy.calls.any()).toBeTruthy(); // error
});

注意::如果要提供组件级服务的自定义实现,则应使用overrideComponent方法,例如:

fixture = TestBed.overrideComponent(ExampleComponent, {
  providers: { provide: PersistanceService, useClass: PersistanceServiceSpy }
})
.createComponent(ExampleComponent);