如何以角度覆盖RxJS主题的​​Jasmine单元测试

时间:2020-01-27 14:25:45

标签: angular jasmine jestjs karma-jasmine angular-test

我是非常新的Jasmine单元测试用例。我的场景可能很简单,但是我不确定如何在下面的课程中介绍ngInit的测试用例。有人可以帮我吗,

export class Component1 implements OnInit {
    details$: Observable<any>; 
    name: string; 
    error: string 

    constructor(private service1: Service1, private service2: Service2) { }

    ngOnInit() {
       this.service1.service1Subject.subscribe( info => {
            if(info['url']){
                this.details$ = this.service2.get(info['url'])
                this.details$.subscribe(
                 (info) => { this.name = info['name']}; 
                 (error) => { this.erro = error['error']}; 
                ); 
            }  
       }); 
    }
}

测试用例:

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

  beforeEach(async(() => {
   TestBed.configureTestingModule({
     declarations: [Component1],
     imports: [
       HttpClientTestingModule, CommonModule
     ],
     providers: [Service1, Service2]
   })
     .compileComponents();
   }));

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

  it('should call Get Data', () => {
      const service2: Service2 = TestBed.get(Service2);
      const spy = jest.spyOn(service2, 'get').mockImplementation(() => {
          return {
             info :  [...],
              name : ''  
          }
      });
      component.ngOnInit();
      expect(spy).toHaveBeenCalled();
  });
});

这里的问题是,我不确定如何模拟service1,RxJS主题。请有人帮我。

1 个答案:

答案 0 :(得分:1)

我看到您正在使用Jest,但是这是我设置组件测试的方式,这些组件测试使用公开Subject的服务。

  1. 为您的所有服务创建模拟
  2. 在测试模块中提供它们
  3. 模拟实现以控制数据流
  4. 执行您的断言

    describe('Component1', () => { 
        let component: Component1;
        let fixture: ComponentFixture<Component1>;
    
        //create mock service objects
        let service1Mock = jasmine.createSpyObj('service1', ['toString']);
        let service2Mock = jasmine.createSpyObj('service2', ['get']);
    
        beforeEach(async(() => {
            TestBed.configureTestingModule({
                declarations: [Component1],
                imports: [
                    HttpClientTestingModule,
                    CommonModule
                ],
                providers: [
                    //Set up the dependency injector, but use the mocks as the implementation
                    { provide: Service1, useValue: service1Mock },
                    { provide: Service2, useValue: service2Mock }
                ]
            }).compileComponents();
        }));
    
        beforeEach(() => {
            //add an observable to your service
            //this will also help reset the observable between each test
            service1Mock.service1Subject = new Subject<any>(); 
        });
    
        beforeEach(() => {
            fixture = TestBed.createComponent(Component1);
            component = fixture.componentInstance;
            fixture.detectChanges();
        });
    
        it('should get the data', () => {
            //configure the mock implementation of "service2.get" to successfully return data
            //You can alternatively use "throw({error: 'some_error'})" to test your "error" case
            service2Mock.get.and.returnValue(of({name: 'some_name'}));
    
            //tell the mock to emit some data!
            service1Mock.service1Subject.next( {url: 'some_url'} );
    
            //Your component subcriptions should handle the event, perform whatever test needs to do
        });
    });
    

我知道Jasmine计划使create spy objects with attributes成为可能,但是我实际上并没有真正使用它。

顺便说一句,如果您不在模板中使用details$,则可以完全消除该变量。

ngOnInit(){
    this.service1.service1Subject.subscribe( info => {
        if(info['url']){
            this.service2.get(info['url']).subscribe(
                (info) => { this.name = info['name']}; 
                (error) => { this.error = error['error']}; 
            ); 
        }  
    });
}