我有一个简单的测试用例,它检查是否单击了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,但这些都不起作用。
答案 0 :(得分: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