Jest.js 测试React组件时如何设置子 prop ?

fykwrbwg  于 2023-01-18  发布在  Jest
关注(0)|答案(1)|浏览(193)

我有这个组件

const InputWithLabel = ({
                          id,
                          value,
                          type = 'text',
                          onInputChange,
                          isFocused,
                          children,
                        }) => {...
return(<>
        <label htmlFor={id} className="label">
                {children}
        </label>
...
</>)}

我正在测试:

describe('InputWithLabel',()=>{
    const inputWithLabelProps={
        id:"search",
        value:"React",
        isFocused:true,
        onInputChange:jest.fn,
        children:[]
    }
    test('check the existence of InputWithLabel',()=>{
        render(<InputWithLabel {...inputWithLabelProps}/>);
        screen.debug();// This to see the renders of the Element 
    });
})

我可以给孩子们什么样的价值:[]来做这个测试。我试过用对象数组,但是不起作用。有什么想法吗?

flvlnr44

flvlnr441#

在我的例子中,这是解决方案,这是组件的调用

<InputWithLabel
          id="search"
          value={searchTerm}
          isFocused
          onInputChange={onSearchInput}
      >
        <strong>Search:</strong>
      </InputWithLabel>

测试将为:

describe('InputWithLabel',()=>{
    const inputWithLabelProps={
        id:"search",
        value:"React",
        isFocused:true,
        onInputChange:jest.fn,
        children:<strong>Search:</strong>
    }
    test('check the existence of InputWithLabel',()=>{
        render(<InputWithLabel {...inputWithLabelProps}/>);
        screen.debug();
    });
})

请注意

<strong>Search:</strong>

是my组件的子级

相关问题