简体   繁体   English

如何覆盖angular中RxJS科目的Jasmine单元测试

[英]How to cover Jasmine unit test for RxJS subject in angular

I am very new Jasmine unit test cases.我很新 Jasmine 单元测试用例。 My scenario may be easy but I am not sure how to cover test case for ngInit for below class. Can someone help me,我的场景可能很简单,但我不确定如何涵盖 class 以下的 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']}; 
                ); 
            }  
       }); 
    }
}

Test case:测试用例:

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();
  });
});

The problem here is, I am not sure how to mock service1, RxJS subject.这里的问题是,我不确定如何模拟 service1, RxJS 主题。 Please someone help me.请有人帮助我。

I see you're using Jest, but here's how I've set up component tests that use a service that expose a Subject .我看到您正在使用 Jest,但这里是我设置组件测试的方式,这些测试使用公开Subject的服务。

  1. Create mocks for all your services为您的所有服务创建模拟
  2. Provide them in your test module在您的测试模块中提供它们
  3. Mock implementations to control the flow of data模拟实现来控制数据流
  4. Perform your assertions执行你的断言

    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 }); });

I know that Jasmine was planning on making it possible to create spy objects with attributes , but I haven't actually used it myself.我知道 Jasmine 计划使创建具有属性的间谍对象成为可能,但我自己实际上并没有使用它。

As an aside, if you're not using details$ in your template, you can eliminate the variable entirely.顺便说一句,如果您不在模板中使用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']}; 
            ); 
        }  
    });
}

Mock the subject first and then add it to mocked service.先模拟主题,然后将其添加到模拟服务中。

 describe('Component1', () => {
    
     let component: Component1;
     let fixture: ComponentFixture<Component1>;
     let mockSubject = new Subject<boolean>();
     mockSubject.next(true);
     let mockService = jasmine.createSpyObj(Service, ['getTheme']);
      
     beforeEach(async () => {
        await TestBed.configureTestingModule({
          declarations: [Component1],
          providers: [{ provide: Service, useValue: mockService }],
        }).compileComponents();
    
        mockService.getTheme.and.returnValue(false);

        mockService.theme$ = mockSubject; <---- assign mocked value
        
        fixture = TestBed.createComponent(Component1);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Angular 4 Jasmine单元测试用例覆盖IF / ELSE条件 - How to cover IF/ELSE condition with Angular 4 Jasmine unit test case Angular和Rxjs:编写单元测试以过滤主题 - Angular and Rxjs: writing unit test for filtering on Subject 如何覆盖抽象类中存在的 eventEmitter 对象的单元测试用例(茉莉花/Angular8) - How can I cover unit test case for eventEmitter object exists in abstract class (jasmine / Angular8) 如何做一个简单的 angular Jasmine 单元测试时使用 RXJS 使用主题的反应方法和调用服务的 stream - How to do a simple angular Jasmine Unit testing when using RXJS reactive approach using a subject and a stream that calls a service 如何在 Angular 中使用 Jasmine 测试 RxJS switchMap? - How to test RxJS switchMap with Jasmine in Angular? 如何模拟 RxJS 主题并在 Angular 单元测试中调用下一个方法 - How to mock RxJS Subject and call next method in Angular unit-test Angular 单元测试,如何将一个主题测试为可观察的 - Angular unit test, how to test a subject as observable 如何覆盖 Angular 中 addEventListener 的单元测试用例 9 - How to cover unit test case for addEventListener in Angular 9 如何使用 angular 的 debounceTime 对 Subject 进行单元测试 - How to unit test Subject with a debounceTime in angular 如何在 Z96A94EDBDB5534E2EFFE465C77478 中覆盖 RXJS pipe function? - How to cover the RXJS pipe function in Jasmine?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM