Search code examples
javascriptnode.jsangularkarma-jasminekarma-coverage

Karma unit test EventEmitter emit and subscribe failed, Cannot read property 'subscribe' of undefined


I'm new to Angular/Node UT, currently, i added karma and jasmine to run unit test, my application is based on Angular7 + Node 8, following Angular test docs, most test cases run successfully, but some cases like @Input @Output(EventEmitter) data test failed. Please see my code and configure as below:

package.json:

    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2"

a.component.ts:

userDetailInit(){
    this.lookupService.genericServiceCall1(this.componentIds.componentUserDetail);
    this.lookupService.compomentJsonEmit.subscribe(async o => {
      // logic
    }, error => {
      this.error("System Error");
    });
  }

lookupService:

    genericServiceCall1(iD) {
      let param = {
        'id': iD
      };
      this.compomentJsonEmit = new EventEmitter<Object>();
      // getData() is a http request and will return data
      this.commonService.getData('Get', param).subscribe(o =>{
        this.compomentJsonEmit.emit(o);
      });
    }

in unit test file agent-details.component.spec.ts:

describe('UserDetailsComponent', () => {

  let spy = {
    compJSONSpy: jasmine.createSpyObj('lookupService', ['genericServiceCall1']),
  }


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ UserDetailsComponent ],
      imports: [FormlyModule.forRoot(), HttpClientTestingModule],
      providers: [
        {provide: CommonService, useValue:  spy.comSpy },
        {provide: LookupService, useValue: spy.compJSONSpy}
      ],
      schemas: [NO_ERRORS_SCHEMA ]
    }).compileComponents();
    fixture = TestBed.createComponent(UserDetailsComponent);
    component = fixture.componentInstance;
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  }));


  it('#timeChange(val) should set selectTimeZone to val', () => {
    compJSONSpyReturn = spy.compJSONSpy.genericServiceCall1.and.returnValue(of(spyReturnJson.UserDetailCompJson));
    component.componentIds = {
      componentUserDetail: 1007
    };

    // error occurred when run component.timeChange(12);
    component.timeChange(12);
    expect(compJSONSpyReturn.calls.any()).toBeDefined();
    expect(component.selectTimeZone).toEqual(12);
  });
});

Karma ussye report:

TypeError: Cannot read property 'subscribe' of undefined
    at userDetailsComponent.subscribe [as userDetailInit] (http://localhost:9876/_karma_webpack_/webpack:/src/app/admin/user-details/user-details.component.ts:77:46)
    at userDetailsComponent.userDetailInit [as timeChange] (http://localhost:9876/_karma_webpack_/webpack:/src/app/admin/user-details/user-details.component.ts:109:14)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/admin/user-details/user-details.component.spec.ts:66:15)
userListComponent #ngOninit() should be run

Solution

  • this.lookupService.compomentJsonEmit is undefined.

    Try:

    const compomentJsonEmitSubject = new BehaviorSubject('hello'); // you can mock it how you like instead of 'hello'
    describe('UserDetailsComponent', () => {
     let spy = {
        compJSONSpy: jasmine.createSpyObj('lookupService', ['genericServiceCall1']),
      }
     spy.compJSONspy.compomentJsonEmit = componentJsonEmitSubject;
     beforeEach(async(() => {
    ....
    

    Then later on in your tests if you want a new value of componentJsonEmit, you can do componentJsonEmitSubject.next('goodbye');