[英]Mock React useRef or a function inside a functional component with enzyme and jest?
Codesanbox link - includes working component Child2.js and working test Child2.test.js Codesanbox 链接-包括工作组件 Child2.js 和工作测试 Child2.test.js
Child2.js Child2.js
import React, { useRef } from "react";
export default function Child2() {
const divRef = useRef();
function getDivWidth() {
if (divRef.current) {
console.log(divRef.current);
}
return divRef.current ? divRef.current.offsetWidth : "";
}
function getDivText() {
const divWidth = getDivWidth();
if (divWidth) {
if (divWidth > 100) {
return "ABC";
}
return "123";
}
return "123";
}
return (
<>
<div id="myDiv" ref={divRef}>
{getDivText()}
</div>
<p>Div width is: {getDivWidth()}</p>
</>
);
}
Child2.test.js Child2.test.js
import React from "react";
import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import Child2 from "../src/Child2";
Enzyme.configure({ adapter: new Adapter() });
it("div text is ABC when div width is more then 100 ", () => {
const wrapper = shallow(<Child2 />);
expect(wrapper.find("#myDiv").exists()).toBe(true);
expect(wrapper.find("#myDiv").text()).toBe("ABC");
});
it("div text is 123 when div width is less then 100 ", () => {
const wrapper = shallow(<Child2 />);
expect(wrapper.find("#myDiv").exists()).toBe(true);
expect(wrapper.find("#myDiv").text()).toBe("123");
});
When i run the tests, obvisouly the offsetWidth of the div is 0, hence i need to find a way to mock the useRef
to return a div element with width or mock the getDivWidth
function to return a desired number for the width.当我运行测试时,显然 div 的 offsetWidth 为 0,因此我需要找到一种方法来模拟
useRef
以返回具有宽度的 div 元素或模拟getDivWidth
function 以返回所需的宽度数字。
How could I achieve that?我怎么能做到这一点? I have searched for a solution, but I am stuck.
我一直在寻找解决方案,但我被卡住了。 There are some examples with class components or using typescript which I have not managed to use.
有一些使用 class 组件或使用 typescript 的示例,我没有设法使用。
You can use jest.mock(moduleName, factory, options) and jest.requireActual(moduleName) APIs to mock useRef
hook except others.您可以使用jest.mock(moduleName, factory, options)和jest.requireActual(moduleName) API 来模拟除其他之外的
useRef
钩子。 Which means other functions and methods of react
are still original version.这意味着
react
的其他功能和方法仍然是原始版本。
Eg例如
index.jsx
: index.jsx
:
import React, { useRef } from 'react';
export default function Child2() {
const divRef = useRef();
function getDivWidth() {
if (divRef.current) {
console.log(divRef.current);
}
return divRef.current ? divRef.current.offsetWidth : '';
}
function getDivText() {
const divWidth = getDivWidth();
if (divWidth) {
if (divWidth > 100) {
return 'ABC';
}
return '123';
}
return '123';
}
return (
<>
<div id="myDiv" ref={divRef}>
{getDivText()}
</div>
<p>Div width is: {getDivWidth()}</p>
</>
);
}
index.test.jsx
: index.test.jsx
:
import React, { useRef } from 'react';
import { shallow } from 'enzyme';
import Child2 from './';
jest.mock('react', () => {
const originReact = jest.requireActual('react');
const mUseRef = jest.fn();
return {
...originReact,
useRef: mUseRef,
};
});
describe('61782695', () => {
it('should pass', () => {
const mRef = { current: { offsetWidth: 100 } };
useRef.mockReturnValueOnce(mRef);
const wrapper = shallow(<Child2></Child2>);
expect(wrapper.find('#myDiv').text()).toBe('123');
expect(wrapper.find('p').text()).toBe('Div width is: 100');
});
it('should pass - 2', () => {
const mRef = { current: { offsetWidth: 300 } };
useRef.mockReturnValueOnce(mRef);
const wrapper = shallow(<Child2></Child2>);
expect(wrapper.find('#myDiv').text()).toBe('ABC');
expect(wrapper.find('p').text()).toBe('Div width is: 300');
});
it('should pass - 3', () => {
const mRef = {};
useRef.mockReturnValueOnce(mRef);
const wrapper = shallow(<Child2></Child2>);
expect(wrapper.find('#myDiv').text()).toBe('123');
expect(wrapper.find('p').text()).toBe('Div width is: ');
});
});
Unit test results with 100% coverage:覆盖率 100% 的单元测试结果:
PASS stackoverflow/61782695/index.test.jsx (9.755s)
61782695
✓ should pass (111ms)
✓ should pass - 2 (15ms)
✓ should pass - 3 (1ms)
console.log
{ offsetWidth: 100 }
at getDivWidth (stackoverflow/61782695/index.jsx:8:15)
console.log
{ offsetWidth: 100 }
at getDivWidth (stackoverflow/61782695/index.jsx:8:15)
console.log
{ offsetWidth: 300 }
at getDivWidth (stackoverflow/61782695/index.jsx:8:15)
console.log
{ offsetWidth: 300 }
at getDivWidth (stackoverflow/61782695/index.jsx:8:15)
-----------|---------|----------|---------|---------|-------------------
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: 3 passed, 3 total
Snapshots: 0 total
Time: 10.885s
package versions: package 版本:
"react": "^16.13.1",
"react-dom": "^16.13.1",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"jest": "^25.5.4",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.