Jest 的 "const mock = jest.fn();" 到底有什么作用?

What does Jest's "const mock = jest.fn();" really do?

我发现这个模拟示例在 tutorial page 上四处流传,但我发现它被如此频繁地用作示例令人困惑。

test("mock return value", () => {
  const mock = jest.fn();
  mock.mockReturnValue("bar");

  expect(mock("foo")).toBe("bar");
  expect(mock).toHaveBeenCalledWith("foo");
});

const mock = jest.fn(); 是否曾经连接到需要模拟的真实函数?如果是这样,它怎么知道要模拟哪个函数?像这样的新随机 mock 的用例是什么?

本文中的示例仅演示jest.fn()的功能。 mock 对象未被待测代码使用。

如前所述,mock 函数提供以下功能:

  • 捕捉通话
  • 设置return值
  • 更改实现

在实际代码中有这样一种情况,函数接受一个对象并调用该对象的方法。在这种情况下,您可以创建一个模拟对象并将其传递给该函数。

例如

// A real function need to be tested, it can be imported from a module
function getUserById(dbc, id) {
  return dbc.query('select * from users where id = ;', [id]);
}

describe('70538368', () => {
  test('should pass', () => {
    const mDbc = {
      query: jest.fn().mockReturnValue({ name: 'teresa teng' }),
    };
    const actual = getUserById(mDbc, '1');
    expect(actual).toEqual({ name: 'teresa teng' });
    expect(mDbc.query).toBeCalledWith('select * from users where id = ;', ['1']);
  });
});