【发布时间】:2020-05-02 10:05:03
【问题描述】:
我有一个模拟如下
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
有人有想法吗?
干杯!
编辑:
我现在的解决方案是像这样模拟它
import ReactHookInview from 'react-hook-inview';
jest.mock('react-hook-inview', () => ({
useInView: jest.fn().mockImplementation(() => {
const setRef = jest.fn();
const observer = jest.fn();
const intersecting = false;
const entry = {
boundingClientRect: {
y: 0,
},
};
return [setRef, intersecting, entry, observer];
}),
}));
在我的测试中,我会这样覆盖:
ReactHookInview.useInView.mockImplementation(() => {
const setRef = jest.fn();
const observer = jest.fn();
const intersecting = true;
const entry = {
boundingClientRect: {
y: 1,
},
};
return [setRef, intersecting, entry, observer];
});
但这不是很漂亮
【问题讨论】:
-
您将
const intersecting = true留在了屏蔽传递参数intersecting的函数中。我不认为这会解决你的问题,尽管因为开玩笑提升了模块模拟。 -
@DrewReese 我对此表示怀疑,因为 Jest 不允许闭包样式引用变量。这可能是因为 Jest 提升了 mocks。
-
@DrewReese 好眼光!不幸的是,我只是把它留在这里,但在我的实际代码中没有犯这个错误:D 我还更新了我的初始帖子
标签: javascript reactjs jestjs react-testing-library