Gabriel Castillo Prada
Gabriel Castillo Prada

Reputation: 4673

Angular Mock field/property with Jasmine / Karma

I'm trying to test a component which uses a Service with a property called inside a method's component. I need to mock and change that property depending on the test.

I have this:

export class XService{
  xProperty:boolean;
}

export class XComponent{

   ctor(private xService:XService){
   }

   xMethod():void{
     if(xService.xProperty){
         //some code
     }
   }
}

I tried it creating a mock and adding the property in beforeEach method

beforeEach(() => {
    /**more code**/
    xServiceMock = jasmine.createSpyObj(['xMethodService']);
    xServiceMock ['xProperty'] = false;
});

That works well until I have to change the value in one of the tests. When I do it, the value is not refreshed.

it('x validation', () => {
    xServiceMock.xProperty = true;
    fixture.detectChanges();
    component.xMethod();<<<-- When it calls the method the change to TRUE is not refreshed
    expect(/****/).toBe(false);
  });

Do you know if I can mock that property with Jasmine? Is it possible?

Upvotes: 3

Views: 5541

Answers (3)

Fateh Mohamed
Fateh Mohamed

Reputation: 21367

you can use a mock for your service

class MockXService extends XService{
   xProperty = false; // set a fake value here    
}

add the service to providers this way

beforeEach(async(() => {
TestBed.configureTestingModule({
  ...,
   declarations: [XComponent],
  providers: [
    { provide: XService, useClass: MockXService },
  ],

})

and your test

it('x validation', () => {
fixture.detectChanges();
component.xMethod();<<<-- When it calls the method the change to TRUE is not refreshed
expect(/****/).toBe(false);
});

Upvotes: 3

Walter Luszczyk
Walter Luszczyk

Reputation: 1522

Using TestBed for testing Angular services makes overload in most cases. Check my answer here

Upvotes: -1

Buczkowski
Buczkowski

Reputation: 2416

This can help you: https://next.angular.io/guide/testing#always-get-the-service-from-an-injector

Basically when you provide mock/spy/stub instead of real service in configureTestingModule you need to get it afterwards with TestBed.get().

Upvotes: 0

Related Questions