В двух разных тестах я хочу смоделировать два разных значения функции в данном сервисе.Я использую:
service = TestBed.get(someService);
spyObj = jest.spyOn(service, 'someFunction').mockReturnValue(of('foo'));
и первый тест проходит хорошо.Затем, если я напишу либо
spyObj.mockReturnValue(of('second foo'));
, либо
spyObj = jest.spyOn(someService, 'someMethod').mockReturnValue(of('foo'));
во втором тесте, полученное значение все равно будет 'foo'.Я пробовал также mockClear
, mockReset
и mockRestore
, и ни один из них, похоже, ничего не делал вообще.Я всегда получаю 'foo'.
Что я должен сделать, чтобы получить другое значение во втором тесте?
У меня есть следующие версии jest
:
"jest": "^24.1.0",
"jest-junit": "^6.3.0",
"jest-preset-angular": "^6.0.2",
Я не могу обновить jest-preset-angular
, потому что у меня эта нерешенная проблема .: - (
Здесь код немного расширен:
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');
});
});