【问题标题】:Jest spy.On() does not call the method in React JsJest spy.On() 不调用 React Js 中的方法
【发布时间】:2021-10-11 22:13:56
【问题描述】:

我为一个方法写了一个测试:

const methods = {
  run: (name) => {
    console.log('run');
    return name;
  }
}

使用const testMethod = jest.spyOn(methods, 'run').mockResolvedValue({});,不会触发console.log('run'),但如果我写:const testMethod = jest.spyOn(methods, 'run');,会触发console.log()。
为什么在第一种情况下没有触发 console.log() 以及如何解决这个问题?

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    当您使用mockResolvedValue 时,您正在用存根替换您的函数。由于存根的目的不是执行函数的真正实现,而只是返回一个虚构的值,因此这种行为是正常的。

    jest.fn().mockResolvedValue({})
    

    相当于:

    jest.fn().mockImplementation(() => Promise.resolve({}));
    

    https://jestjs.io/docs/mock-function-api#mockfnmockresolvedvaluevalue

    更新:

    如果你想验证你的函数是否被调用并且它是否返回了一个特定的值,那么:

    const spy = jest.spyOn(methods, 'run');
    
    const myName = 'John Doe';
    
    // Call the method...
    
    expect(spy).toBeCalled();
    expect(spy).toHaveReturnedWith(myName);
    

    【讨论】:

    • 在我的情况下如何避免这个问题?我需要执行具有特定值的函数。
    • 试试这样的const run = methods.run; const testMethod = jest.spyOn(methods, 'run').mockImplementation(() => { run(); return { returnValue: 100 }; });
    • 我觉得我不太了解你的目标。
    • 你想用特定的参数调用你的方法吗?或者调用它并返回一个特定的值?
    • 我想测试我的方法是否被调用,以及它是否返回一个特定的值。我改变了我上面的功能。你能帮忙吗?
    猜你喜欢
    • 2021-10-16
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2015-12-21
    • 2017-04-25
    • 2021-07-10
    相关资源
    最近更新 更多