Search code examples
angularunit-testingjasminekarma-jasmineangular-unit-test

Getting error while unit testing of angular component method?


I am running a unit test which is failing. Please look at my code:

This is my typescript file:

  allData: any;
  constructor(@Inject(MAT_DIALOG_DATA) private data,
    private dialogRef: MatDialogRef<MyComponent>,
    private _service: SampleService,
    private _router: Router) {
  }
  ngOnInit() {
    this.loadValue();
  }
  loadValue() {
    this._service.returnData().subscribe(res => {
      this.allData = res;
    })
  }

This is my service file implementation:

  //SampleService
  returnData(){
    const users=[{ id: "01", name:"Andrew" }, { id: "02", name:"Shaun" }];
    return of(users);
  }

This is my spec file:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      imports: [MatDialogModule],
      providers: [
        {
          provide: MAT_DIALOG_DATA, useValue: { action: "add" },
        },
        {
          provide: MatDialogRef, useValue: { MyComponent}
        },
        {
          provide: Router
        },
        {
          provide: SampleService
        }
      ]
    }).compileComponents()
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    el = fixture.debugElement;
    component = fixture.componentInstance;
    sampleservice = new SampleService();
  })

My test case:

  it("should call the loadvalue and fill the allData", () => {
    let users = [{ id: "01", name: "John" }, { id: "02", name: "Wick" }];
    component.loadValue();
    spyOn(sampleservice, 'returnData').and.returnValue(of(users));
    expect(component.allData).toBe(users);
  })

I want to call the loadvalue() method and expecting the allData variable to filled with the dummy response using spyOn. But when I run this test case, I get error as:

TypeError: Cannot read property 'returnData' of undefined

What am I doing wrong here? Any help would be much appreciated. Thanks!


Solution

  • Try this:

    sampleservice = TestBed.get(SampleService);
    

    And replace

    {
      provide: SampleService
    },
    

    by just :

    SampleService,
    

    And in your test:

    it("should call the loadvalue and fill the allData", () => {
      spyOn(sampleservice, 'returnData').and.returnValue(of(users));
      fixture.detectChanges();
    
      let users = [{ id: "01", name: "John" }, { id: "02", name: "Wick" }];
      component.loadValue();
      expect(component.allData).toBe(users);
    })