【问题标题】:Unable to test a service method in angular using jasmine无法使用 jasmine 以角度测试服务方法
【发布时间】:2021-05-14 02:26:55
【问题描述】:

我正在用 Angular 进行单元测试。在component.ts 中,在ngOnInit 中,我有一个服务方法调用,如下所示:

ngOnInit(){
   this.DomainManagementService.getVerifiedDomains().then(res => {
      this.claimedDomains = res.filter(domain => {
        return domain.status === 'claimed';
      });
    });
}

我从getVerifiedDomains() 方法获取数据,然后应用过滤器方法仅过滤出声明的域。最后,我将过滤后的域存储在this.claimedDomains 中。 现在我需要测试this.claimedDomains的长度是否大于0。这个怎么做?请帮我写测试用例。

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    你必须先模拟domainMainagementService,我会使用jasmine.createSpyObj

    ....
    let mockDomainManagementService: jasmine.SpyObj<DomainManagementService>;
    ....
    beforeEach(waitForAsync(() => {
       mockDomainManagementService = jasmine.createSpyObj<DomainManagementService>('DomainManagementService', ['getVerifiedDomains']);
       TestBed.configureTestingModule({
         ....
         providers: [{ provide: DomainManagementService, useValue: mockDomainManagementService }],
       }).compileComponents();
       // Make sure this is there before the first fixture.detectChanges().
       // The first fixture.detectChanges() calls ngOnInit.
       // Mock the return value here.
       mockDomainManagementService.getVerifiedDomains.and.returnValue(Promise.resolve([
         { status: 'claimed' },
      ]))
    }));
    
    it('should set claimedDomains', async () => {
       // wait until all promises are resolved with fixture.whenStable()
       await fixture.whenStable();
       expect(component.claimedDomains.length).toBe(1);
    });
    

    【讨论】:

    • 是的,我已经做到了。但是在模拟 getVerifiedDomains 方法时,我该怎么办?
    • 过滤完成后如何检查 this.claimedDomains 是否包含某些内容?
    • 抱歉,我按回车键太早了。我已经编辑了我的回复,您现在可以查看。它应该有助于您入门。编辑:我刚刚意识到这是一个承诺,而不是一个可观察的,所以我现在做 Promise.resolve。
    • 非常感谢。我的公司可能在开玩笑。但我从你的解决方案中找出了一切
    【解决方案2】:

    你需要这样做来模拟你的服务调用:

    // This will create a function that will inject the service in your test
    function setup() {
        const domainManagementService = fixture.debugElement.injector.get(DomainManagementService);
    
        return { domainManagementService };
    }
    
    // - This is your test scenario
    it('Load Claimed Domains ', () => {
        const { domainManagementService} = setup();
        spyOn(domainManagementService, 'getVerifiedDomains').and.returnValue(Promise.resolve([{status: 'claimed'},{status: 'claimed'}]));
        component.ngOnInit();
        expect(domainManagementService.getVerifiedDomains).toHaveBeenCalled();
        expect(component.claimedDomains.length).toBe(2);
    });
    

    但请记住正确模拟您的服务响应,以便您拥有正确的“claimedDomains”。

    【讨论】:

    • 不可能是of([...,我觉得应该是Promise.resolve
    • component.ngOnInit()这样写对吗?
    • 是的,没问题
    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多