【问题标题】:Jest how to assert that function is not called开玩笑如何断言该函数未被调用
【发布时间】:2018-05-22 05:10:09
【问题描述】:

在 Jest 中有 tobeCalledtoBeCalledWith 之类的函数来检查是否调用了特定函数。 有什么方法可以检查一个函数没有被调用吗?

【问题讨论】:

标签: jestjs


【解决方案1】:

只需使用not

expect(mockFn).not.toHaveBeenCalled()

jest documentation

【讨论】:

    【解决方案2】:

    not 对我不起作用,抛出一个Invalid Chai property: toHaveBeenCalled

    但是使用带有零的toHaveBeenCalledTimes 可以解决问题:

    expect(mock).toHaveBeenCalledTimes(0)

    【讨论】:

    • 问题是关于 Jest
    • 什么意思?我的答案是使用 jest 的解决方案
    • 我想他的意思是Chai 错误。但是 mabe Jest 在引擎盖下使用(或曾经使用过)Chai?
    【解决方案3】:

    请遵循 jest 中的文档: https://jestjs.io/docs/en/mock-functions#mock-property

    所有模拟函数都有这个特殊的 .mock 属性,其中保存了有关函数调用方式和函数返回内容的数据。 .mock 属性还跟踪每次调用的 this 值,因此也可以检查它:[...]

    这些模拟成员在测试中非常有用,可以断言这些函数如何被调用、实例化或返回什么:

    // The function was called exactly once
    expect(someMockFunction.mock.calls.length).toBe(1);
    

    或者……

    // The function was not called
    expect(someMockFunction.mock.calls.length).toBe(0);
    

    【讨论】:

      【解决方案4】:

      最新版本的 Jest(22.x 及更高版本)收集了相当不错的模拟函数调用统计信息,请查看 their docs

      calls 属性显示调用次数、传递给模拟的参数、从中返回的结果等等。您可以直接访问它,作为mock 的属性(例如@Christian Bonzelet 在他的回答中建议的方式):

      // The function was called exactly once
      expect(someMockFunction.mock.calls.length).toBe(1);
      
      // The first arg of the first call to the function was 'first arg'
      expect(someMockFunction.mock.calls[0][0]).toBe('first arg');
      
      // The second arg of the first call to the function was 'second arg'
      expect(someMockFunction.mock.calls[0][1]).toBe('second arg');
      

      我个人更喜欢这种方式,因为它可以为您提供更大的灵活性并保持代码更简洁,以防您测试产生不同数量调用的不同输入。

      不过,您也可以使用 Jest 最近的 expect (spy matchers aliases PR) 的速记别名。我猜.toHaveBeenCalledTimes 很适合这里:

      test('drinkEach drinks each drink', () => {
        const drink = jest.fn();
        drinkEach(drink, ['lemon', 'octopus']);
        expect(drink).toHaveBeenCalledTimes(2); // or check for 0 if needed
      });
      

      在极少数情况下,您甚至可能需要考虑编写自己的夹具来进行计数。例如,如果您非常注重调节或使用状态,它可能会很有用。

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2018-08-14
        • 2018-02-14
        • 2021-04-03
        • 2018-12-27
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多