0

How do I return two different values from this mock service when I am providing it in the initial test for the component? I want to be able to return two different values for two different tests from mock service

describe('example', () => { let component: ExampleComponent; let fixture: ComponentFixture<ExampleComponent>; let mockService: Partial<MockService>; beforeEach(async(() => { mockService = { mockMethodSpy: jasmine.createSpy('mockMethod') }; TestBed.configureTestingModule({ declarations: [ ExampleComponent], imports: [], providers: [ { provide: MockService, useValue: mockService }, ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ExampleComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should return true from mock service', () => { expect(mockService.mockMethodSpy).toBe(true); }); it('should return false from mock service', () => { expect(mockService.mockMethodSpy).toBe(false); }); }); 
2
  • 1
    Why are you asserting/testing what your spy returns, instead of testing the subject component? Commented Dec 29, 2020 at 1:18
  • Does this answer your question? stackoverflow.com/a/16208124/2358409 Commented Dec 29, 2020 at 7:27

1 Answer 1

1

spy can be configured on the fly. just call the configuring methods, and it will behave differentrly

it('should 1', () => { mockService.mockMethodSpy.and.returnValue(12345); expect(mockService.mockMethodSpy()).toBe(12345); }); it('should 2', () => { mockService.mockMethodSpy.and.callFake(() => 54321); expect(mockService.mockMethodSpy()).toBe(54321); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

@milanf, what is wrong with this answer? Looks like what you asked.
Doesn't work for me, in OP question the type of let mockService: Partial<MockService> is messing things up in the test as its not a jasmine spy object. Would help if you provided a full example that compiles.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.