How to unit test a method of react component?
You are almost there. Just change your expect to this: expect(wrapper.instance().checkBoxChecked()).equals(true); You can go through this link to know more about testing component methods using enzyme
You are almost there. Just change your expect to this: expect(wrapper.instance().checkBoxChecked()).equals(true); You can go through this link to know more about testing component methods using enzyme
Add it to your test case file. import React from ‘react’; import Adapter from ‘enzyme-adapter-react-16’; import { shallow, configure } from ‘enzyme’; configure({adapter: new Adapter()}); test(‘message box’, ()=> { … })
To test a component (with Jest) that contains <Route> and withRouter you need to import Router in you test, not in your component import { BrowserRouter as Router } from ‘react-router-dom’; and use it like this app = shallow( <Router> <App /> </Router>);
To mock useSelector use can do this import * as redux from ‘react-redux’ const spy = jest.spyOn(redux, ‘useSelector’) spy.mockReturnValue({ username:’test’ })
OK, found a solution. Should use jest.useFakeTimers() Note: Put the code above just after import section in your test file.
.contains receives a React Node or array of Nodes as an argument. Instead, use .find: expect(wrapper.find(‘selector’).exists()).toBeTruthy()
I think what you want is: input.simulate(‘change’, { target: { value: ‘Hello’ } }) Here’s my source. You shouldn’t need to use render() anywhere to set the value. And just FYI, you are using two different render()‘s. The one in your first code block is from Enzyme, and is a method on the wraper object … Read more
Updated for Jest 27+ For jest 27+, you can also use process.nextTick: await new Promise(process.nextTick); (Thanks to Adrian Godong in the comments) Original Answer Here’s a snippet that waits until pending Promises are resolved: const flushPromises = () => new Promise(setImmediate); Note that setImmediate is a non-standard feature (and is not expected to become standard). … Read more
#1 Using Jest This is how I use the Jest mock callback function to test the click event: import React from ‘react’; import { shallow } from ‘enzyme’; import Button from ‘./Button’; describe(‘Test Button component’, () => { it(‘Test click event’, () => { const mockCallBack = jest.fn(); const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>)); button.find(‘button’).simulate(‘click’); expect(mockCallBack.mock.calls.length).toEqual(1); … Read more
As per the Enzyme docs: mount(<Component />) for Full DOM rendering is ideal for use cases where you have components that may interact with DOM apis, or may require the full lifecycle in order to fully test the component (ie, componentDidMount etc.) vs. shallow(<Component />) for Shallow rendering is useful to constrain yourself to testing … Read more