你好,我有一个我想用jest + enzyme测试的scrollBar!我意识到我必须先模拟该功能 我检查了一些教程,但它不起作用,该功能始终未定义 这就是我尝试过的:
it('One step scroll working', function () {
const scrollBySpy = jest.fn()
global.document.scrollBy = scrollBySpy;
wrapper.find('Button').at(1).prop('onDoubleClick')()
expect(scrollBySpy).toHaveBeenCalled()
})
我们用Simulation('click')调用的函数
scrollToTheEnd = (direction: string) => {
if (direction !== 'right' && direction !== 'left') return
let walk = direction === 'right' ? 3000 : -3000
const slider: HTMLElement = this.state.scrollRef.current;
slider.scrollBy(walk, 0)
}
我在函数scrollToTheEnd内部有此错误
TypeError: slider.scrollBy is not a function
有什么想法吗?
答案 0 :(得分:0)
这是单元测试解决方案:
index.tsx
:
import React, { Component } from 'react';
export interface ISomeComponentState {
direction: string;
scrollRef: {
current: HTMLElement | null;
};
}
class SomeComponent extends Component<any, ISomeComponentState> {
constructor(props) {
super(props);
this.state = {
direction: 'right',
scrollRef: {
current: null
}
};
}
scrollToTheEnd = (direction: string) => {
if (direction !== 'right' && direction !== 'left') return;
let walk = direction === 'right' ? 3000 : -3000;
const slider: HTMLElement = this.state.scrollRef.current as HTMLElement;
slider.scrollBy(walk, 0);
};
render() {
return <button onDoubleClick={() => this.scrollToTheEnd(this.state.direction)}>scroll to the end</button>;
}
}
export default SomeComponent;
index.spec.tsx
:
import React from 'react';
import SomeComponent, { ISomeComponentState } from './';
import { shallow } from 'enzyme';
describe('SomeComponent', () => {
test('should scroll to the end', () => {
const mCurrent = document.createElement('div');
mCurrent.scrollBy = jest.fn();
const mState: ISomeComponentState = { direction: 'right', scrollRef: { current: mCurrent } };
const wrapper = shallow(<SomeComponent></SomeComponent>);
expect(wrapper.text()).toBe('scroll to the end');
wrapper.setState(mState);
wrapper.find('button').simulate('doubleClick');
expect(mCurrent.scrollBy).toBeCalledWith(3000, 0);
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/56639450/index.spec.tsx (7.287s)
SomeComponent
✓ should scroll to the end (15ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 94.12 | 62.5 | 100 | 100 | |
index.tsx | 94.12 | 62.5 | 100 | 100 | 21,22 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.459s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56639450