React-Mock window.scroll类似于使用Jest Enzyme的preventDefault()

问题描述 投票:0回答:1

我有一个简单的测试用例,它检查是否单击了onSubmit按钮以及是否调用了preventDefault()

这很好,但是我在测试window.scrollTo()时遇到问题。有人可以帮助我建议如何以类似方式模拟window.scrollTo

describe("should render label", () => {
let mockPreventDefault;
let mockEvent;

beforeEach(() => {
    jest.clearAllMocks();
    onSubmit = jest.fn();
    validate = jest.fn();
    mockPreventDefault = jest.fn();
  });

it("should call preventDefault on onSubmit call", () => {
    instance.onSubmit(mockEvent());
    expect(mockPreventDefault).toHaveBeenCalledTimes(1);
  });

});

PS-我尝试了StackOverflow中提到的所有方法。尝试使用global.scrollTo代替window.scrollTo,但我也尝试使用spyOn,但这些都不起作用。

javascript reactjs react-native jestjs enzyme
1个回答
0
投票

这里是单元测试解决方案:

index.jsx

import React, { Component } from 'react';

class SomeComponent extends Component {
  onSubmit = (e) => {
    e.preventDefault();
    window.scrollTo({ top: 0 });
  };

  render() {
    return (
      <div>
        <form onSubmit={this.onSubmit}></form>
      </div>
    );
  }
}

export default SomeComponent;

index.spec.jsx

import React from 'react';
import { shallow } from 'enzyme';
import SomeComponent from './';

describe('SomeComponent', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });
  it('should handle submit correctly', async () => {
    window.scrollTo = jest.fn();
    const wrapper = shallow(<SomeComponent></SomeComponent>);
    const mEvent = { preventDefault: jest.fn() };
    wrapper.find('form').simulate('submit', mEvent);
    expect(mEvent.preventDefault).toHaveBeenCalledTimes(1);
    expect(window.scrollTo).toBeCalledWith({ top: 0 });
  });
});

单元测试结果覆盖率100%:

 PASS  src/stackoverflow/59494359/index.spec.jsx (13.043s)
  SomeComponent
    ✓ should handle submit correctly (16ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.jsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.192s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59494359

© www.soinside.com 2019 - 2024. All rights reserved.