Timbo773
Timbo773

Reputation: 183

Angular unit test - changing a mock service class's method return for individual tests

in my unit test I have a mock service class that I'm using, MockWorkflowService, which has a method getActiveTask. The default functionality of this method is needed for the bulk of the tests, however there are a couple of tests that I need to override this method and have it return null. However I'm not having any luck with doing so (see test at the bottom of the code block):

class MockWorkflowService {
  getActiveTask() {
    return new Action({
      name: 'test',
      value: 4
    })
  }
}

describe('MyComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MyComponent
      ],
      providers: [
        TranslateService,
        { provide: WorkflowService, useClass: MockWorkflowService }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should ...', () => {
    // TRYING TO DO SOMETHING LIKE
    MockWorkflowService.getActiveTask = () => null;
  });

})

I tried doing MockWorkflowService.prototype.getActiveTask = () => null, which works for the individual test I want to override it with, but then the method returns null for all remaining tests.

Any help would be much appreciated, thanks.

Upvotes: 3

Views: 3704

Answers (1)

Srikar Phani Kumar M
Srikar Phani Kumar M

Reputation: 1384

This is what you need to do when you want to over-ride only for that particular test. What you are doing is over-riding all the instances of that service, which is wrong. You can follow this:

// Define the service here: 
describe('MyComponent', () => {
  let workflowService: WorkFlowService // Add this line
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MyComponent
      ],
      providers: [
        TranslateService,
        { provide: WorkflowService, useClass: MockWorkflowService }
      ]
    })
      .compileComponents();
  }));

// In before each, create an instance of the service
 beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    workFlowService = TestBed.get(WorkflowService); // Add this line
    // TestBed.get should be TestBed.inject if you're using Angular 9+
  });


it('should ...', () => {
  // Spy on the service and return null
  // This will call the mock service class and return null for this test case

  spyOn(workFlowService, 'getActiveTask').and.returnValue(null);
  component.yourComponentMethodName();
  expect(component.yourComponentMethodName).toHaveBeenCalled();
});

Upvotes: 3

Related Questions