组件文件中的模拟值

mock value inside the component file

请问组件中是否有变量useState,作为判断里面的元素出现与否的条件。如何模拟变量?这样我就可以在值为 'login'.

的情况下测试条件内的元素
   const [dataHistory,seDataHistory] = useState("")
   const [data,setData] = useState("firstTimeLogin")
        
    const func2 = () => {
     getData({
      item1: "0",
     }).
     then((res) => {
       funct();
     })
   }

   const funct = () => 
     {setData("login")}
        
   return  
     {data === "firstTimeLogin" && (
        <div><button onClick="funct2()">next</button></div>
     )}

     {data === "login" && (
        <div>flow login</div>
      )}

您可以创建一个按钮并在按钮的 onClick 上调用 funct()

首先,您需要为按钮添加 data-testid

{data === "firstTimeLogin" && (
   <div><button onClick="funct2" data-testid="next-button">next</button></div>
)}

你调用了onClick="funct2()"是在re-rendering后立即触发funct2,所以我修改为onClick="funct2".

请注意,您也可以在事件点击按钮中使用 next 内容,但我更喜欢使用 data-testidnext 内容更固定.

在你的测试文件中,你应该模拟 getData 并调用 fireEvent.click 来触发 funct2()

import { screen, fireEvent, render } from '@testing-library/react';

//'/getData' must be the actual path you're importing for `getData` usage
jest.mock('/getData', () => {
   return {
      getData: () => new Promise((resolve) => { resolve('') }) // it's mocked, so you can pass any data here
   }
})

it('should call funct', async () => {
   render(<YourComponent {...yourProps}/>)
   const nextButton = await screen.findByTestId("next-button"); //matched with `data-testid` we defined earlier
   fireEvent.click(nextButton); //trigger the event click on that button
   const flowLoginElements = await screen.findByText('flow login'); //after state changes, you should have `flow login` in your content
   expect(flowLoginElements).toBeTruthy();
})