@jonrsharpe 的建议是组件测试的一般原则,但是你的问题是特例,涉及到DOM的一些属性和方法,比如offsetWidth
和getBoundingClientRect()
方法。jsdom
无法返回的运行环境和浏览器运行环境下的渲染引擎返回的结果导致方法offsetWidth
返回的和 属性值getBoundingClientRect()
始终为0
。
所以这里我们需要 mock ref
。
ref
这里的mock也很特别。除了jest.mock()
用于部分模拟之外,该ref.current
属性将react
在组件安装后分配。为了拦截这个操作,我们需要创建一个ref
带有current
对象属性的mock对象,使用Object.defineProperty()
方法为这个属性定义getter
and ,拦截属性赋值。setter
ref.current
jest.spyOn
方法采用 accessType 的第三个可选参数,它可以是“get”或“set”,当您想分别监视 getter 或 setter 时,这被证明是有用的。
例如
index.tsx
:
import React, { useEffect, useRef } from 'react';
export default function App() {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
console.log(ref.current?.offsetWidth);
}, [ref]);
return <div ref={ref}>app</div>;
}
index.test.tsx
:
import { render } from '@testing-library/react';
import React, { useRef } from 'react';
import { mocked } from 'ts-jest/utils';
import App from './';
jest.mock('react', () => {
return {
...jest.requireActual<typeof React>('react'),
useRef: jest.fn(),
};
});
const useMockRef = mocked(useRef);
describe('66332902', () => {
afterEach(() => {
jest.clearAllMocks();
});
afterAll(() => {
jest.resetAllMocks();
});
test('should mock ref and offsetWidth', () => {
const ref = { current: {} };
Object.defineProperty(ref, 'current', {
set(_current) {
if (_current) {
jest.spyOn(_current, 'offsetWidth', 'get').mockReturnValueOnce(100);
}
this._current = _current;
},
get() {
return this._current;
},
});
useMockRef.mockReturnValueOnce(ref);
render(<App />);
});
});
测试结果:(见日志)
PASS examples/66332902/index.test.tsx (9.518 s)
66332902
✓ should mock ref and offsetWidth (39 ms)
console.log
100
at examples/66332902/index.tsx:6:13
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.106 s