我有一个模拟如下
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
有人有想法吗?
欢呼!
如评论中所述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];
});
}