Tengo una función que devuelve JSX Element.
myFunction.jsx const myFunction = (props) => { // ... do something with props return <MyElement {...newProps} /> } // MyElement.jsx export const MyElement = (props) => { // ... return some jsx }Mi objetivo es verificar que myFunction devuelva un elemento con el conjunto correcto de accesorios. Pero no quiero incluir el renderizado de MyComponent para probarlo, así que me burlé de él. Intenté probarlo así:
const mockFn = jest.fn(); jest.mock('.../path-to-my-component/MyComponent, () => ({ MyComponent: (props) => { mockFn(props) return 'my-component' } })) // .... myFunction(someProps) expect(mockFn).toHaveBeenCalled() // mockFn have been called 0 times expect(mockFn).toHaveBeenCalledWith(someProps)Pero ambas expectativas fueron fallidas.
Así es como finalmente lo manejo
jest.mock('../../MyComponent', () => ({ MyComponent: (props) => { return <div {...props} />; }, })); test('my test', () => { const Component = myFunction(props); expect(Component.props).toBe(/* that's the place where you can check props */) });Algo como esto podría permitirle no representar myComponent si sus accesorios no son de la forma que desea después de que propsIsOk los haya verificado.
// myFunction.jsx const myFunction = (props) => { // ... do something with props const propsIsOk = (props) => { // Check props' properties and returns a boolean } if(propsIsOk(newProps)){ return(<MyElement {...newProps} />) } else { return(<></>) } } // MyElement.jsx export const MyElement = (props) => { // ... return some jsx }