【发布时间】:2019-10-28 20:26:29
【问题描述】:
在两个不同的测试中,我想模拟给定服务中函数的两个不同值。我用:
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,因为我有this non-solved problem。 :-(
这里的代码有点扩展:
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');
});
});
【问题讨论】:
-
尝试在
afterEach挂钩中调用jest.restoreAllMocks()。另外,如果这可能有帮助,我不知道jestjs.io/docs/en/mock-functions#mock-return-values -
没用 :-(