简体   繁体   中英

Unit testing for service in Angular

I am trying to create unit testing for service I have import data service in spec file.

Then I am calling in beforeach Method.

 providers: [
    { provide: dataservice}    
  ],

I am getting this error

TypeError: Cannot read property 'setNumber' of undefined

this.dataService.setNumber(null);

As per the below user I added

const spyDataService = jasmine.createSpyObj('DataService', ['setNumber '])

in before each

How to get rid of this error I am trying like below i am getting error and i modifed this into

  it('should be create data service', () => {    
     expect(DataService).setNumber;
    });

  it('should be create data service', () => {
    expect(service.setBCNumber).toHaveBeenCalledWith(null);
  }); 

but still I am getting the same error.

You must provide the class instead of the instance. if you want to provide a instance, you must use useValue like this:

{
  provide: DataService,
  useValue: dataServiceMock
}

Also, expect is on an instance, not a class, hence

expect(DataService).setNumber;

should be

expect(dataService.setNumber).toHaveBeenCalledWith(null);

You also need to set the dataServiceMock to a mock instance like in the example:

let dataServiceMock: jasmine.SpyObj<DataService>;

beforeEach(() => {
  const spyDataService = jasmine.createSpyObj('DataService', ['setNumber ']);

...
    {
      provide: DataService,
      useValue: spyDataService
    }
...

I recommand you the official angular site for testing: https://angular.io/guide/testing-services

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM