【问题标题】:Unit test for method that uses a service使用服务的方法的单元测试
【发布时间】:2021-11-05 16:15:27
【问题描述】:

我正在为组件编写单元测试。它的一种方法使用服务,它给了我一个cannot read property 'then' of undefined 错误。

我已经看到如何在测试中调用服务,但我正在尝试使用一种方法来调用我的规范文件之外的服务。

规格

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        imports: [...],
        declarations: [MyComponent],
        providers: [...],
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should save', () => {
    ...
    component.myMethod();
  });

});

组件

  public myMethod() {
      ...
      this.myService.something(this.item).then((resp) => {
       // Error comes from here
      });
    }
  }

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    您可以通过模拟服务方法以多种方式解决此问题:

    • 使用 spyOn
    it('should save', () => {
      const service = TestBed.inject(MyService);
      spyOn(service , 'something').and.returnValue(Promise.resolve('test'));
      component.myMethod();
    });
    
    let userServiceStub: Partial<MyService>;
    
    myServiceStub = {
      something: () => Promise.resolve('test'),
    };
    
    // configureTestingModule
    providers: [
      { provide: MyService, useValue: MockService(myServiceStub ) }
    ]
    
    // configureTestingModule
    providers: [
      MockProvider(MyService, { something: () => Promise.resolve('test') })
    ]
    

    还有其他方法,但其中一种应该可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      相关资源
      最近更新 更多