我的项目是采用react + ts来写的,项目中要写单元测试,于是采用了Jest库, 主要用的package有
react-test-renderer react-test-renderer/shallow @jest/globals
这里只展示shallow的用法,主要用来测导航栏组件
1 import {createRenderer} from "react-test-renderer/shallow"; 2 import {afterEach, beforeEach, describe, expect, it} from "@jest/globals"; 3 import * as React from "react"; 4 5 6 describe("render element", () => { 7 //创建renderer 8 const wrapper = createRenderer(); 9 let elements: JSX.Element; 10 let leftEle: JSX.Element; 11 let linkContainerEle: JSX.Element; 12 beforeEach(() => { 13 //浅渲染组件 14 wrapper.render(renderFrame()); 15 16 //获取到最外层的某个元素 17 elements = wrapper.getRenderOutput(); 18 19 20 21 //get element 22 leftEle = elements.props.children[0]; 23 24 25 26 //get element 27 linkContainerEle = elements.props.children[1]; 28 }); 29 30 31 32 afterEach(() => { 33 wrapper.unmount(); 34 }); 35 36 37 //这里是测渲染,(Link的to属性) 38 it("the link of logo icon connect to ‘testNav‘", () => { 39 //get element 40 const logoIconEle = leftEle.props.children[0]; 41 expect(logoIconEle.props.to).toBe("testNav"); 42 }); 43 44 // 这里测事件---这个方法可行,但是原理我不是很明白 45 it("when click ‘icon‘, hidden/display box", () => { 46 // mock event 47 const event: {nativeEvent: {stopImmediatePropagation: () => void}} = { 48 nativeEvent: { 49 stopImmediatePropagation: () => { 50 // do nothing 51 }, 52 }, 53 }; 54 // simulate user action, click icon 55 //不直接找到icon元素,调用它的点击事件,而是找到点击事件对应的函数,直接调这个函数 56 wrapper.getMountedInstance()["changeShowBox"](event); 57 58 59 60 // so state showBox become true 61 expect(wrapper.getMountedInstance()["state"]["showBox"]).toBeTruthy; 62 }); 63 64 65 66 67 });
上述两个方法只能说可行,具体的用法可能不太正确
使用react-test-renderer/shallow写测试
原文:https://www.cnblogs.com/pandacat5/p/14768285.html