我正在尝试测试一个组件,该组件包含一个包含react-intersection-observer的子组件,但我总是得到一个错误
我试图导入库,但仍然失败。这是初始测试
beforeEach(() => {
testContainer = document.createElement("div");
document.body.appendChild(testContainer);
subject = memoize(() =>
mount(<FilterNav {...props} />, { attachTo: testContainer })
);
});
afterEach(() => {
testContainer.remove();
});
context("the main filter is shown initially", () => {
it("sets focus on the primary filter", () => {
subject();
const input = testContainer.querySelector(".main-input");
expect(document.activeElement).toEqual(input);
});我收到此错误,未捕获ReferenceError:未定义IntersectionObserver
有没有办法让我模仿IntersectionObserver?
谢谢
发布于 2019-08-09 14:11:48
我实际上能够用一个模拟函数来解决这个问题,并将它包含在窗口对象中
const observe = jest.fn();
window.IntersectionObserver = jest.fn(function() {
this.observe = observe;
});发布于 2019-12-04 20:58:38
您可以在模拟文件中执行类似的操作(例如,我将其命名为intersectionObserverMock.js ):
const intersectionObserverMock = () => ({
observe: () => null
})
window.IntersectionObserver = jest.fn().mockImplementation(intersectionObserverMock);在测试文件中直接导入文件,如下所示:
import '../__mocks__/intersectionObserverMock';这将解决您的"IntersectionObserver未定义“的问题
发布于 2019-08-08 13:36:14
使用IntersectionObserver的组件也有同样的问题。
更新:我们需要在测试文件中直接导入intersection。
import 'intersection-observer';
https://stackoverflow.com/questions/57008341
复制相似问题