Reactjs 测试反应组件、模拟道具

Reactjs 测试反应组件、模拟道具,reactjs,Reactjs,各位, 这里是前端新手。试图了解如何正确地将mockprops传递给组件的构造函数 class MyComponent extends React.Component { constructor(props) { super(props); let dataToDecode = QueryString.parse(props.location.search).data; const data = QueryString.parse(Base

各位, 这里是前端新手。试图了解如何正确地将mock
props
传递给组件的构造函数

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        let dataToDecode = QueryString.parse(props.location.search).data;
        const data = QueryString.parse(Base64.decode(dataToDecode));
        this.state = {
            email: data.email,
            ...
        };
    ...

那么,如何在react中模拟
道具呢?
testinglibrary/react
jest
能否对此提供帮助

i、 e.测试需要覆盖正确的uri和不正确的uri。
https://domain/path?data=somebase64encodedstring

it('renders without crashing', () => {
    const div = document.createElement('div');
    ReactDOM.render(<MyComponent />, div);
});
it('呈现而不崩溃',()=>{
const div=document.createElement('div');
ReactDOM.render(,div);
});

谢谢

我建议您使用该库,它允许您对组件进行浅层渲染或完全渲染。酶使您能够轻松测试组件的输出

在这种情况下,使用它就足够了

这是一种使用模拟道具浅渲染组件的方法

import * as React from 'react';
import { shallow } from 'enzyme';

describe('<MyComponent />', () => {

  it('sample test', () => {
    const myComponent = <MyComponent 
      location={mockLocation} 
      otherProps={otherMockProps}
    />
    const wrapper = shallow(myComponent);
    // expect().....
  });

})
import*as React from'React';
从“酶”导入{shall};
描述(“”,()=>{
它('样本测试',()=>{
常量myComponent=
常量包装=浅(myComponent);
//expect()。。。。。
});
})
从上面可以看到,我们在组件上调用了浅层渲染API,
shallow()
,以及所需的道具。从那时起,您可以执行其他形式的行为,例如调用方法或监视方法调用,并测试所需的行为