使用 react-jss 和酶时如何测试组件方法?
How do I test a component method when using react-jss and enzyme?
我基本上有这个问题:
https://github.com/airbnb/enzyme/issues/208
但是我的组件包装在 jss withStyles
包装器中。我正在使用 shallow
method created by Material-UI as outlined here.
例如:
class Button extends React.Component {
handleClick() {
// Do something here
}
render() {
// Component here
}
}
const styles = {
root: {}
}
export withStyles(styles)(Button);
问题是 - wrapper.instance().handleClick()
会抛出 handleClick() is not a function
。
如何访问组件本身?
您可以使用 dive 访问您的组件。
MUI 似乎还带有“dive”功能:
The createShallow() function can be used for this situation. Aside from wrapping the enzyme API, it provides a dive and untilSelector option.
import { createShallow } from '@material-ui/core/test-utils';
describe('<MyComponent />', () => {
let shallow;
before(() => {
shallow = createShallow({dive: true}); // Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result.
});
it('should work', () => {
const wrapper = shallow(<MyComponent />);
});
});
我基本上有这个问题:
https://github.com/airbnb/enzyme/issues/208
但是我的组件包装在 jss withStyles
包装器中。我正在使用 shallow
method created by Material-UI as outlined here.
例如:
class Button extends React.Component {
handleClick() {
// Do something here
}
render() {
// Component here
}
}
const styles = {
root: {}
}
export withStyles(styles)(Button);
问题是 - wrapper.instance().handleClick()
会抛出 handleClick() is not a function
。
如何访问组件本身?
您可以使用 dive 访问您的组件。
MUI 似乎还带有“dive”功能:
The createShallow() function can be used for this situation. Aside from wrapping the enzyme API, it provides a dive and untilSelector option.
import { createShallow } from '@material-ui/core/test-utils';
describe('<MyComponent />', () => {
let shallow;
before(() => {
shallow = createShallow({dive: true}); // Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result.
});
it('should work', () => {
const wrapper = shallow(<MyComponent />);
});
});