小编mal*_*dao的帖子

是否可以验证 Angular 组件内的服务调用?

我在尝试验证 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我想验证在调用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 …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine karma-jasmine angular

3
推荐指数
1
解决办法
2942
查看次数

标签 统计

angular ×1

jasmine ×1

karma-jasmine ×1

unit-testing ×1