In two different tests I want to mock two different values of a function in a given service. I use:
service = TestBed.get(someService);
spyObj = jest.spyOn(service, 'someFunction').mockReturnValue(of('foo'));
and the first test runs well. Then if I write either
spyObj.mockReturnValue(of('second foo'));
or
spyObj = jest.spyOn(someService, 'someMethod').mockReturnValue(of('foo'));
in the second test, the value I get is still 'foo'. I tried also mockClear
, mockReset
and mockRestore
and none of them seems to do anything at all. I always get 'foo'.
What should I do to get a different value in my second test?
I have the following versions of jest
:
"jest": "^24.1.0",
"jest-junit": "^6.3.0",
"jest-preset-angular": "^6.0.2",
I can't update jest-preset-angular
because I have this non-solved problem. :-(
Here the code a bit more expanded:
describe('whatever', () => {
let component: SomeComponent;
let fixture: ComponentFixture<SomeComponent>;
let someService: SomeService;
let spyObj: jest.Mock<Observable<any>, [string | string[], object?]>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SomeModule.forRoot()
],
declarations: [ SomeComponent ],
providers: [ SomeService ]
})
.compileComponents();
}));
beforeEach(() => {
someService = TestBed.get(SomeService);
spyObj = jest.spyOn(someService, 'someMethod').mockReturnValue(of('foo'));
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
fixture.destroy();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should check someFunction when someService returns "foo"', () => {
component.someFunction(); // This function uses the value of someService
// Debugging inside someFunction I get "foo"
expect(component.something).toEqual('foo');
});
it('should check someFunction when someService returns "second foo"', () => {
spyObj.mockReturnValue(of('second foo'));
// this does not work either:
// spyObj = jest.spyOn(someService, 'someMethod').mockReturnValue(of('second foo'));
component.someFunction(); // This function uses the value of someService
// Debugging inside someFunction I still get "foo"
expect(component.something).toEqual('second foo');
});
});