0

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!

1 Answer 1

1

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);
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.