笑话模拟交叉口

时间:2019-11-15 20:41:01

标签: mocking jestjs stenciljs

我有以下方法:

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,有任何建议

2 个答案:

答案 0 :(得分:1)

由于您的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();

答案 1 :(得分:0)

这个解决方案对我有用。

基本上你只是把 IntersectionMock 放在 beforeEach 里面

beforeEach(() => {
  // IntersectionObserver isn't available in test environment
  const mockIntersectionObserver = jest.fn();
  mockIntersectionObserver.mockReturnValue({
    observe: () => null,
    unobserve: () => null,
    disconnect: () => null
  });
  window.IntersectionObserver = mockIntersectionObserver;
});