我正在尝试使测试覆盖率超过80%,而这条线阻止了这种情况的发生。测试应用程序时,似乎无法触发if语句。该行为在客户端视图中按预期方式运行,但在测试文件中失败,因此我无法弄清原因。
“ handleClickOutside”功能是我要测试的功能。
class UserInfo extends Component {
constructor(props) {
super(props);
this.popup = null;
this.state = { user: this.props.user, showMenu: false };
this.handleToggleTheme = this.handleToggleTheme.bind(this);
}
componentDidMount() {
document.addEventListener("click", this.handleClickOutside, true);
}
componentWillUnmount() {
document.removeEventListener("click", this.handleClickOutside, true);
}
handleClickOutside = event => {
const domNode = ReactDOM.findDOMNode(this.popup);
console.log(domNode);
console.log(event);
if (domNode && !domNode.contains(event.target)) {
console.log('Hit');
this.setState({ showMenu: false });
event.stopPropagation();
}
};
handleToggleTheme() {
this.props.onToggleTheme();
}
render() {
return (
<Root>
<ThemeControlWrapper>
<Switch onChange={this.handleToggleTheme} />
<ThemeIcon src={SunIcon} alt="Light Mode Icon" />
</ThemeControlWrapper>
<UserInfoWrapper
ref={userInfo => {
this.anchor = userInfo;
}}
onClick={() =>
this.setState(state => {
return { showMenu: !state.showMenu };
})
}
className={this.props.className}
>
<UserPhoto src={Config.PublicFolder + "/user/photo.jpg"} />
<UserName>{this.state.user.name}</UserName>
{this.state.showMenu ? <ArrowUpIcon /> : <ArrowDownIcon />}
</UserInfoWrapper>
<Popup
anchor={this.anchor}
show={this.state.showMenu}
ref={popupElement => {
this.popup = popupElement;
}}
>
<Menu>
<MenuItem>
<LogoutIcon />
<LogoutText>Logout</LogoutText>
</MenuItem>
</Menu>
</Popup>
</Root>
);
}
}
这是此功能的测试
const defaultUser = {
appsWithDashboard: apps
};
const withDualThemeAndUserWrapper = ({
WrappedComponent,
customUser = { permissions: [], roles: [], partitions: [] }
}) => props => (
<DualThemeProvider>
<UserProvider user={customUser}>
<WrappedComponent {...props} />
</UserProvider>
</DualThemeProvider>
);
let WithThemeAndUserContext = withDualThemeAndUserWrapper({
WrappedComponent: () => <UserInfo user={{ name: "Andrew" }} />,
customUser: defaultUser
});
let wrapper;
describe("handleClickOutside", () => {
test("Should fire handleClickOutside", () => {
wrapper.instance().handleClickOutside({
target : <div className="hello">Hello</div>});
expect(wrapper.state("showMenu")).toBeTruthy();
wrapper.instance().handleClickOutside({
target : <div className="goodbye">Goodbye</div>});
expect(wrapper.state("showMenu")).toBeFalsy();
})
});
如何运行测试,以便测试“ handleClickOutside”执行所有可能的结果。谢谢