【问题标题】:Jest Mock IntersectionObserverJest Mock IntersectionObserver
【发布时间】:2020-03-12 01:00:33
【问题描述】:

我有以下方法:

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 没有被调用,任何建议

【问题讨论】:

    标签: mocking jestjs stenciljs


    【解决方案1】:

    这个解决方案对我有用。

    基本上你只是把 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;
    });

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-02-25
        • 2021-10-11
        • 2019-06-21
        • 2020-04-02
        • 2022-12-02
        • 1970-01-01
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多