有没有办法从茉莉花间谍中模拟功能

Is there a way to mock functions from a jasmine Spy

我正在使用 jasmine 创建一个间谍对象,并返回一个对象,我可以从我返回的对象中模拟函数吗?

例如:

let mockService = jasmine.createSpyObj(['fun']);
mockService.fun.and.returnValue({value: 1});

我试图在这个例子中模拟 get 函数:

let x = service.fun();
x.get();

只需使用 jasmine.createSpyObj() 方法为 service.fun() 的 return 值创建间谍对象。

describe('70304592', () => {
  it('should pass', () => {
    const funSpy = jasmine.createSpyObj(['get']);
    funSpy.get.and.returnValue('1');
    let serviceSpy = jasmine.createSpyObj(['fun']);
    serviceSpy.fun.and.returnValue(funSpy);
    const x = serviceSpy.fun();
    expect(x.get()).toBe('1');
  });
});

update:如果对象有属性和方法,可以这样创建spy obj:

describe('70304592', () => {
  it('should pass', () => {
    const funSpy = jasmine.createSpyObj('fun', {}, { get: jasmine.createSpy(), value: 'please upvote xD' });
    funSpy.get.and.returnValue('1');
    let serviceSpy = jasmine.createSpyObj(['fun']);
    serviceSpy.fun.and.returnValue(funSpy);
    const x = serviceSpy.fun();
    expect(x.get()).toBe('1');
    expect(x.value).toBe('please upvote xD');
  });
});

请参阅 Spying on properties 文档