【问题标题】:Jest: How can I get the arguments called in jest mock function?Jest:我怎样才能得到在 jest 模拟函数中调用的参数?
【发布时间】:2021-03-07 06:49:10
【问题描述】:

我正在学习使用 jest 模拟进行手动模拟,现在我想在 jest 模拟函数中调用参数,这是我的解决方案。

 expect(mockLogin).toHaveBeenCalledWith(
      {
        "email": "test@mail.com", 
        "password": "password", 
        "remember_me": false
       }
    );

现在当我运行npm test 时,我得到以下结果。

我无法弄清楚如何在我的预期结果中添加"auth/login" 路径的问题,我尝试了以下方法,但不幸的是它不起作用。

   expect(mockLogin).toHaveBeenCalledWith("/auth/login", {
        "email": "test@mail.com", 
        "password": "password", 
        "remember_me": false
       });

我需要做什么才能将auth/login 添加到我的预期结果中?

【问题讨论】:

  • 你能发布你的测试代码吗?也许还有你正在测试的代码。

标签: javascript reactjs unit-testing axios jestjs


【解决方案1】:

肯定有其他事情发生。

这是一个有效的简单示例:

describe('example', () => {
    test('mock called with', () => {
        const mock = jest.fn();
        const signin = {
            "email": "test@mail.com",
            "password": "password",
            "remember_me": false
        };
        mock('/auth/login', signin);

        expect(mock).toHaveBeenCalledWith('/auth/login', {
            "email": "test@mail.com",
            "password": "password",
            "remember_me": false
           });
    });
});

【讨论】:

    【解决方案2】:

    你可以试试mockFn.mock.calls

    expect(mockLogin.mocks.call[0][0]).toEqual("/auth/login");
    expect(mockLogin.mocks.call[0][1]).toEqual({
      "email": "test@mail.com", 
      "password": "password", 
      "remember_me": false
    });
    

    【讨论】:

    • TypeError: 无法读取未定义的属性“调用”
    • 你在模拟这个函数吗?
    • 哪个函数???这里是模拟的 api ibb.co/61sX5K5
    【解决方案3】:
    expect(mockLogin).toHaveBeenCalledWith(['/auth/login', {
      "email": "test@mail.com",
      "password": "password", 
      "remember_me": false
    }]);
    

    toHaveBeenCalledWith 需要参数数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-29
      • 2018-10-01
      • 2018-09-14
      • 2022-07-01
      • 2021-01-22
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      相关资源
      最近更新 更多