【问题标题】:Difference between jest mockImplementation() and mockImplementationOnce()开玩笑 mockImplementation() 和 mockImplementationOnce() 之间的区别
【发布时间】:2021-12-16 05:27:39
【问题描述】:

我与 Jest mockImplementation() 合作已经有一段时间了。我在jest 中遇到了mockImplementationOnce()。我读过它,但我不太确定它是如何工作的。谁能解释其中的区别?我似乎找不到任何具体的内容。

【问题讨论】:

    标签: javascript typescript jestjs


    【解决方案1】:

    Documentation

    根据文档,mockImplementation() 接受一个应该用作模拟实现的函数。因此,基本上,您可以通过将函数传递给函数来模拟函数。

    mockImplementationOnce() 接受一个函数,该函数将用作对模拟函数的一次调用的模拟实现。所以,有了这个,一个人可以模拟一次函数。还提到它可以被链接起来,这样每次调用都会返回不同的结果。

    以下是来自文档的mockImplementationOnce() 示例:

    const myMockFn = jest.fn(() => 'default')
      .mockImplementationOnce(() => 'first call')
      .mockImplementationOnce(() => 'second call');
    
    console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
    // 'first call', 'second call', 'default', 'default'
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 2019-06-11
      • 2017-07-26
      • 2020-05-24
      相关资源
      最近更新 更多