React 测试库:测试发送到模拟子组件的 props

bil*_*ill 6 mocking reactjs jestjs react-testing-library

使用 jest 和 React 测试库。

这看起来很基本,但我却错过了它。如何模拟子组件,但测试父组件是否使用正确的 props 调用它?在本例中,我想测试parent.js并模拟子组件。

父.js

import Child from './child'
const Parent = (props) => {
  const {firstname} = props;

  <Child name={firstname} />
}
Run Code Online (Sandbox Code Playgroud)

测试.js

import Parent from '../parent'
jest.mock('./child');

it('should render properly'), () => {
   render(<Parent firstname='bob'/>);
   expect('child').toBeCalledWith({ name: 'bob' });
}
Run Code Online (Sandbox Code Playgroud)

Red*_*cer 2

jest.fn()您应该使用并测试调用它的 props 来模拟 Child 模块。

这可能会有所帮助: https://dev.to/d_ir/verifying-children-passed-to-react-mock-components-2mf9