将参数传递给jest.mock

问题描述 投票:1回答:1

我有一个模拟如下

jest.mock('react-hook-inview', () => {
  const setRef = jest.fn();
  const observer = jest.fn();
  const intersecting = true;
  const entry = {
    y: 0,
  };
  return [setRef, intersecting, entry, observer];
});

这里我想更改intersecting值。如何将其从一项测试更改为另一项测试?我试图使用类似工厂的东西:

const inView = (intersecting) => {
  jest.mock('react-hook-inview', () => {
    const setRef = jest.fn();
    const observer = jest.fn();
    const entry = {
      y: 0,
    };
    return [setRef, intersecting, entry, observer];
  });
}

并像这样使用

  it('is invisible by default', () => {
    const text = 'Test';
    const { container } = render(<Reveal>{text}</Reveal>);
    inView(false);
    expect(container.firstChild).not.toBeVisible();
  });

  it('is visible when in view', () => {
    const text = 'Test';
    const { container } = render(<Reveal>{text}</Reveal>);
    inView(true);
    expect(container.firstChild).toBeVisible();
  });

无论如何抛出

The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: intersecting

有人有想法吗?

欢呼!

javascript reactjs jest react-testing-library
1个回答
0
投票

如评论中所述jest.mock被挂起,jest.doMock不会发生这种情况https://jestjs.io/docs/en/jest-object#jestdomockmodulename-factory-options

尝试在代码中替换它,您应该可以访问外部范围变量。

const inView = (intersecting) => {
  jest.doMock('react-hook-inview', () => {
    const setRef = jest.fn();
    const observer = jest.fn();
    const entry = {
      y: 0,
    };
    return [setRef, intersecting, entry, observer];
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.