I'm a little new to React and currently working with version 16.
The problem here is that I have converted only my App component to a class-based component from a function-based component. And I need to update the test file for this component.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
listCourses: [
{
id: 1,
name: 'ES6',
credit: 60
},
{
id: 2,
name: 'Webpack',
credit: 20
},
{
id: 3,
name: 'React',
credit: 40
}
],
listNotifications: [
{
id: 1,
value: "New course available",
type: "default"
},
{
id: 2,
value: "New resume available",
type: "urgent"
},
{
id: 3,
type: "urgent",
html: {
__html: getLatestNotification()
}
}
]
}
}
componentDidMount() {
this.handleKeyPress();
}
componentWillUnmount() {
window.removeEventListener("keydown", this.handleKeyPress);
}
handleKeyPress = () => {
window.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.key === 'h') {
alert('Logging you out');
this.props.logOut();
}
})
}
render() {
return (
<>
<Notifications listNotifications={this.state.listNotifications} />
<div className='App' style={{ position: 'relative' }}>
<Header />
<div className='App-body'>
{this.props.isLoggedIn ? <CourseList listCourses={this.state.listCourses} /> : <Login />}
</div>
<Footer />
</div>
</>
);
}
}
App.defaultProps = {
isLoggedIn: true,
logOut: () => { }
}
App.propTypes = {
isLoggedIn: PropTypes.bool,
logOut: PropTypes.func
}
export default App;
I need to write a test that verifies that when the keys control and h are pressed the logOut function, passed as a prop, is called and the alert function is called with the string Logging you out.
In the AppTest.js file this is what I have done.
describe('<App />', () => {
it('should verify that when the ctrl + h keys are pressed, the logout() passed as prop is called', () => {
const logOutMock = jest.fn();
const mountComp = mount(<App />)
mountComp.simulate('keyDown', {key: 'h', ctrlKey: true});
expect(logOutMock).toHaveBeenCalledTimes(1);
expect(window.alert).toHaveHaveBeenCalledWith('Logging you out');
});
}
Here are the errors I received;
console.error
The above error occurred in the <img> component:
in img (created by Header)
in div (created by Header)
in Header (created by App)
in div (created by App)
in App (created by WrapperComponent)
in WrapperComponent
Consider adding an error boundary to your tree to customize error handling behavior.
Visit
64 | it('should verify that when the ctrl + h keys are pressed, the logout() passed as prop is called', () => {
65 | const logOutMock = jest.fn();
> 66 | const mountComp = mount(<App logOut={logOutMock}/>)
&
TypeError: symbol is not a function
64 | it('should verify that when the ctrl + h keys are pressed, the logout() passed as prop is called', () => {
65 | const logOutMock = jest.fn();
> 66 | const mountComp = mount(<App logOut={logOutMock}/>)