gpt4 book ai didi

mocking - Jest 模拟 IntersectionObserver

转载 作者:行者123 更新时间:2023-12-01 23:04:52 24 4
gpt4 key购买 nike

我有以下方法:

    componentDidLoad() {
this.image = this.element.shadowRoot.querySelector('.lazy-img');
this.observeImage();
}

observeImage = () => {
if ('IntersectionObserver' in window) {
const options = {
rootMargin: '0px',
threshold: 0.1
};

this.observer = new window.IntersectionObserver(
this.handleIntersection,
options
);

this.observer.observe(this.image);
} else {
this.image.src = this.src;
}
};

我尝试测试 IntersectionObserver.observe 调用,如下所示:

    it('should create an observer if IntersectionObserver is available', async () => {
await newSpecPage({
components: [UIImageComponent],
html: `<ui-image alt="Lorem ipsum dolor sit amet" src="http://image.example.com"></ui-image>`
});

const mockObserveFn = () => {
return {
observe: jest.fn(),
unobserve: jest.fn()
};
};

window.IntersectionObserver = jest
.fn()
.mockImplementation(mockObserveFn);

const imageComponent = new UIImageComponent();
imageComponent.src = 'http://image.example.com';

const mockImg = document.createElement('img');
mockImg.setAttribute('src', null);
mockImg.setAttribute('class', 'lazy-img');

imageComponent.element.shadowRoot['querySelector'] = jest.fn(() => {
return mockImg;
});
expect(imageComponent.image).toBeNull();
imageComponent.componentDidLoad();

expect(mockObserveFn['observe']).toHaveBeenCalled();
});

但是无法使其工作,我的mockObserveFn.observe还没有被调用,有什么建议

最佳答案

您的 mockObserveFn.observe 尚未被调用,因为它不存在。

您可能会收到以下错误:

Matcher error: received value must be a mock or spy function

你可以像这样定义你的模拟

const observe = jest.fn();
const unobserve = jest.fn();

// you can also pass the mock implementation
// to jest.fn as an argument
window.IntersectionObserver = jest.fn(() => ({
observe,
unobserve,
}))

然后你可以期待:

expect(observe).toHaveBeenCalled();

关于mocking - Jest 模拟 IntersectionObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58884397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com