Is it possible to wrap each individual test in a wrapper component? - reactjs

I am using material-UI components in my React components. Therefore I will need to apply the <MuiThemeProvider></MuiThemeProvider> component around all my components in my tests.
My components are located in individual folders:
./src/components/Header/Header.tsx
./src/components/Header/Header.test.ts
./src/components/Header/...
./src/components/Footer/Footer.tsx
./src/components/Footer/Footer.test.ts
./src/components/Footer/...
// etc.
A test would have to look like the following:
import React from 'react';
import { render } from '#testing-library/react';
import Header from './Header';
it('matches snapshot', () => {
const container = render(
// This theme provider is necessary since my components depend on it.
// But rather don't want to include this in all my components.
<MuiThemeProvider theme={theme}>
<Header />
</MuiThemeProvider>
);
expect(container).toMatchSnapshot();
});
But now I'd have to define the MuiThemeProvider in each of my tests.
Is it possible to do this once for all my tests?

Found it: https://testing-library.com/docs/react-testing-library/setup
Turns out it's a react-testing-library thing.
You can modify the render function to wrap a component (provider) in the render method.
Simply change the import of the render function:
Create the function containing with the 'wrapper' component:
// test-utils.js
import { render } from '#testing-library/react'
import { ThemeProvider } from 'my-ui-lib'
import { TranslationProvider } from 'my-i18n-lib'
import defaultStrings from 'i18n/en-x-default'
const AllTheProviders = ({ children }) => {
return (
<ThemeProvider theme="light"> // here it is
<TranslationProvider messages={defaultStrings}>
{children}
</TranslationProvider>
</ThemeProvider>
)
}
const customRender = (ui, options) =>
render(ui, { wrapper: AllTheProviders, ...options })
// re-export everything
export * from '#testing-library/react'
// override render method
export { customRender as render }
And then start using it like this:
// my-component.test.js
- import { render, fireEvent } from '#testing-library/react';
+ import { render, fireEvent } from '../test-utils';

You can mock your higher-order component using jest.mock.
It can something like following
jest.mock("hoc-module", () => {
return {
hocFunction: function(hocConf) {
return function(component) {
component.defaultProps = {
...component.defaultProps,
mockPropKey: mockPropValue
};
return component;
};
}
};
});
P.S: I wrote the above code on the fly.

Related

Failing to mock child react component in tests

There are a bunch of articles and examples about this one, but for some reason, nothing seems to work.
I have a react component that has a child component. And, for simplicity's sake, I want to mock the child component in the test.
The component looks like this:
...
import { ProjectTeam } from '../../assignment/project-team/component';
export const ProjectOverview: React.FC<ProjectOverviewProps> = ({ projectId }) => {
...
return (
<>
...
<Box flex={1}>
<ProjectTeam projectId={projectId} />
</Box>
...
</>
);
};
The ProjectTeam component:
export const ProjectTeam: React.FC<ProjectTeamProps> = ({ projectId }) => {
// just a standard component...
};
And here is the test:
import React from 'react';
import configureMockStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import { render } from '#testing-library/react';
import { I18nextProvider } from 'react-i18next';
import { generateProject } from '../../testing/generators/project';
import { ProjectOverview } from './component';
import { NGStateProvider } from '../../react/providers/route-provider/component';
import { testAngularRouter } from '../../testing/testAngularRouter';
import { DefaultProjectCollection, DefaultUtilizationCollection } from '../store/model';
import { DefaultApaActionCollection } from '../../apa/model';
import i18n from '../../testing/i18n';
import thunk from 'redux-thunk';
describe('ProjectOverview', () => {
let mockStore = null;
const project = generateProject();
beforeEach(() => {
jest.mock('../../assignment/project-team/component', () => ({ ProjectTeam: 'ProjectTeam' }));
mockStore = configureMockStore([thunk])({
projects: { DefaultProjectCollection, ...{ entities: { [project.id]: project } } },
toolUtilizations: DefaultUtilizationCollection,
apaActions: DefaultApaActionCollection,
});
});
test('renders correctly', () => {
const { asFragment } = render(
<NGStateProvider router={testAngularRouter}>
<Provider store={mockStore}>
<I18nextProvider i18n={i18n}>
<ProjectOverview projectId={project.id} />
</I18nextProvider>
</Provider>
</NGStateProvider>,
);
expect(asFragment()).toMatchSnapshot();
});
});
My assumption, that jest.mock(...) should simply replace the child component in test mode. However, it does not. The whole component is trying to render as is.
Here is one of the articles I was referring to: https://thoughtbot.com/blog/mocking-react-components-with-jest
Try moving the jest.mock call outside. I would say right at the top, just before and outside the describe section.
Jest needs to know about mocked component before it starts executing the test file in question.
The article which you reference, has this info,
Alternatively, you can put it within a __mocks__ folder next to the component if that is your preference.

wrap the root component in a <Provider>,or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect

I want to test component by unit test , I don't know how to render the component , it makes an error. I can use only "React-testing-library"
Error : Could not find "store" in the context of "Connect(BaseSignUp)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(BaseSignUp) in connect options.
As your component uses your Redux state, you need to wrap it with a Provider.
For example like this
const Wrapper = ({ children }) => (
// you could just use your normal Redux store or create one just for the test
<Provider store={store}>{children}</Provider>
);
render(<BaseSignup />, { wrapper: Wrapper });
You need to create a different generic render wrapper to resolve these issue as majorly all the component ll require the store access
For eg: I have created this wrapper and exported it with name as rtlRender
import { render } from '#testing-library/react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { Provider } from 'react-redux'
import ReduxStore from "../redux/store";
const queryClient = new QueryClient();
const rtlRender = component => render(<Provider store={ReduxStore.store}>
<QueryClientProvider client={queryClient}>
{component}
</QueryClientProvider>
</Provider>)
export default rtlRender
and now in my test file I use this rtlRender
import { screen } from '#testing-library/react'
import NewUsers from './NewUsers'
import rtlRender from '../../../utils/rtlRender'
describe('New User', () => {
test('Proper Text', () => {
rtlRender(<NewUsers userDetails={[]} />)
const addUserHeading = screen.getByText('Add user')
expect(addUserHeading).toBeInTheDocument();
})
})

Problems testing a Redux + React app with enzyme:

I have this component
import React, { useEffect } from 'react';
import './App.css';
import { connect } from 'react-redux';
import { CircularProgress } from '#material-ui/core';
import { loadPhones } from './redux/actions/actions.js';
import TablePhones from './Table.js';
const mapStateToProps = (state) => state;
function mapDispatchToProps(dispatch) {
return {
loadPhones: () => {
dispatch(loadPhones());
},
};
}
export function App(props) {
useEffect(() => {
props.loadPhones();
}, []);
if (props.phones.data) {
return (
<div className="App">
<div className="introductoryNav">Phones</div>
<TablePhones phones={props.phones.data} />
</div>
);
}
return (
<div className="gridLoadingContainer">
<CircularProgress color="secondary" iconStyle="width: 1000, height:1000" />
<p className="loadingText1">Loading...</p>
</div>
);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
For whom ive written
import React from 'react';
import { render } from '#testing-library/react';
import { Provider } from "react-redux";
import App from './App';
import { shallow, mount } from "enzyme";
import configureMockStore from "redux-mock-store";
const mockStore = configureMockStore();
const store = mockStore({});
describe('App comp testing', () => {
it("should render without throwing an error", () => {
const app = mount(
<Provider store={store}>
<App />
</Provider>
).dive()
expect(app.find('.introductoryNav').text()).toContain("Phones");
});
})
But that test keeps failing
ypeError: Cannot read property 'data' of undefined
I also tried importing App as {App} instead and using shallow testing, but no luck. It gives the same erros, so im left without access to the context, and I cant keep doing my tests
How can I solve this?
You could use the non-default export of your component here and shallow render test if you pass your component the props and don't try to mock the store (if I recall correctly).
I was thinking something like this might work, tesing the "pure" non-store connected version of the component. This seems to be a popular answer for this question as this was asked (in a different way) before here:
import React from 'react';
import { App } from './App';
import { shallow } from "enzyme";
// useful function that is reusable for desturcturing the returned
// wrapper and object of props inside of beforeAll etc...
const setupFunc = overrideProps => {
const props = {
phones: {
...phones, // replace with a mock example of a render of props.phones
data: {
...phoneData // replace with a mock example of a render of props.phones.data
},
},
loadPhones: jest.fn()
};
const wrapper = shallow(<App {...props} />);
return {
wrapper,
props
};
};
// this is just the way I personally write my inital describe, I find it the easiest way
// to describe the component being rendered. (alot of the things below will be opinios on test improvements as well).
describe('<App />', () => {
describe('When the component has intially rendered' () => {
beforeAll(() => {
const { props } = setupFunc();
});
it ('should call loadPhones after the component has initially rendered, () => {
expect(props.loadPhones).toHaveBeenCalled();
});
});
describe('When it renders WITH props present', () => {
// we should use describes to section our tests as per how the code is written
// 1. when it renders with the props present in the component
// 2. when it renders without the props
beforeAll(() => {
const { wrapper, props } = setupFunc();
});
// "render without throwing an error" sounds quite broad or more like
// how you would "describe" how it rendered before testing something
// inside of the render. We want to have our "it" represent what we're
// actually testing; that introductoryNave has rendered with text.
it("should render an introductoryNav with text", () => {
// toContain is a bit broad, toBe would be more specific
expect(wrapper.find('.introductoryNav').text()).toBe("Phones");
});
it("should render a TablePhones component with data from props", () => {
// iirc toEqual should work here, you might need toStrictEqual though.
expect(wrapper.find('TablePhones').prop('phones')).toEqual(props.phones);
});
});
describe('When it renders WITHOUT props present', () => {
it("should render with some loading components", () => {
expect(wrapper.find('.gridLoadingContainer').exists()).toBeTruthy();
expect(wrapper.find('CircularProgress').exists()).toBeTruthy();
expect(wrapper.find('.loadingText1').exists()).toBeTruthy();
});
});
});

TypeError: dispatch is not a function when testing with react-create-app jest and enzyme

I'm trying to setup testing on a new project created with react-create-app. Which now seems to be using React 16 and Jest 3 (which supposedly had some breaking changes, or maybe that was enzime). I'm getting an error similar to this post TypeError: dispatch is not a function when I try to test a method using JEST
TypeError: dispatch is not a function
at App.componentDidMount (src/components/App.js:21:68)
import React from 'react';
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import { App } from '../components/App';
import configureStore from '../state/store/configureStore';
window.store = configureStore({
slider: {
mainImageIndex: 0,
pageNum: 1,
perPage: 4,
},
});
const appTest = (
<Provider store={window.store}>
<App />
</Provider>
);
describe('App', () => {
it('should render without crashing', () => {
mount(appTest);
});
});
Originally I just tried to do this:
import React from 'react';
import { mount } from 'enzyme';
import { App } from '../components/App';
describe('App', () => {
it('should render without crashing', () => {
mount(<App />);
});
});
Which threw this error
Invariant Violation: Could not find "store" in either the context or props of "Connect(Form(SearchForm))". Either wrap the root component in a , or explicitly pass "store" as a prop
Code for App.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { searchPhotos } from '../state/actions/searchPhotos';
import { setMainImageIndex, setFirstPage } from '../state/actions/slider';
import Slider from './Slider';
import SearchForm from './SearchForm';
import Error from './Error';
import '../styles/App.css';
export class App extends Component {
componentDidMount() {
const { dispatch } = this.props;
dispatch(searchPhotos(window.store));
}
searchPhotosSubmit = () => {
const { dispatch } = this.props;
dispatch(setFirstPage());
dispatch(setMainImageIndex(0));
dispatch(searchPhotos(window.store));
}
render() {
const { fetchError } = this.props;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Flickr Slider in React.js</h1>
<SearchForm onSubmit={this.searchPhotosSubmit} />
</header>
{!fetchError ? <Slider /> : <Error />}
</div>
);
}
}
export default connect(state => ({
fetchError: state.fetchError,
form: state.form,
slider: state.slider,
}))(App);
Please not that you export both presentational component (as named export) and container component (as default export) in App.js. Then in your tests you import and use the presentational component using:
import { App } from '../components/App';
but you should import connected container component instead using:
import App from '../components/App'; // IMPORTANT! - no braces around `App`
Since you're using component that is not connected to Redux store dispatch prop is not injected as prop. Just use correct import and it should work.
For more details about importing default and named exports please check this doc. About presentational and container components you can read here.

How to test a TextField Material-UI element with React Jest?

I built up a component with React and Material-UI. I'm using React and Redux.
my index.jsx looks like this:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import configureStore from '../store/configureStore';
import Routes from '../routes/routes';
import '../styles/main.less';
const store = configureStore();
render(
<Provider store={store}>
<MuiThemeProvider>
<Routes />
</MuiThemeProvider>
</Provider>,
document.getElementById('app'),
);
My component InputSearch looks like this:
import React, { PropTypes, Component } from 'react';
import TextField from 'material-ui/TextField';
class InputSearch extends Component {
...
render() {
return (
...
<TextField
defaultValue={this.props.keyword}
ref={(input) => { this.input = input; }}
autoFocus
hintText='Type a keyword'
errorText={this.state.errorText}
floatingLabelText='Search for keyword'
style={styles.textField}
/>
);
}
}
InputSearch.propTypes = {
keyword: PropTypes.string.isRequired,
resetSearch: PropTypes.func.isRequired,
searchBooks: PropTypes.func.isRequired,
toggleResultsOpacity: PropTypes.func.isRequired,
firstSearch: PropTypes.bool.isRequired,
};
export default InputSearch;
I'm using Airbnb Enzyme and Jest to build unit tests.
My test to the InputSearch component looks like this:
import React from 'react';
import { shallow, mount } from 'enzyme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import TextField from 'material-ui/TextField';
import InputSearch from '../components/InputSearch/InputSearch';
const resetSearchMock = jest.fn();
const searchBooksMock = jest.fn();
const toggleResultsOpacityMock = jest.fn();
const setup = () => {
const props = {
keyword: '',
resetSearch: resetSearchMock,
searchBooks: searchBooksMock,
toggleResultsOpacity: toggleResultsOpacityMock,
firstSearch: true,
};
const wrapper = shallow(<MuiThemeProvider><InputSearch {...props} /></MuiThemeProvider>);
return {
props,
wrapper,
};
};
describe('Initial test', () => {
test('Shows error message when input search is empty.', () => {
const { wrapper, props } = setup();
expect(wrapper.find(TextField).getValue()).toEqual('');
});
}
However, I'm getting the following error:
TypeError: wrapper.find(...).getValue is not a function
Can anyone help me reach the right way to check the value of the Material UI TextField, please?
I have been writing test for few days using mocha, enzyme and chai. The problem that comes with testing material-ui is these are inturn react component so they cannot be tested as you test regular html elements.
You can find out what property change by printing the whole component, like
console.log(wrapper.find('TextField').debug());
This will print the whole element for you, you can notice that the TestField has value prop which is what you are suppose to check because this prop is what decided the value in the TextField
So the code will go like this:
describe('Initial test', () => {
test('Shows error message when input search is empty.', () => {
const { wrapper, props } = setup();
expect(wrapper.find(TextField).props().value).to.equal('');
});
}
This is how I have been testing the TextField component.
Hope you find it helpful.
Please, if someone has a better solution answer my question. After some attempts, I figured out how to test some material UI components. Basically, we need to find the native html elements (input, button, etc) inside the material UI components via enzyme find. I also realized that "shallow", only do a one level deep search, as #Andreas Köberle said in comments below. To force a deep search in the DOM tree we need to use enzyme "mount". http://airbnb.io/enzyme/docs/api/ReactWrapper/mount.html
Here is my new test code.
import React from 'react';
import { shallow, mount } from 'enzyme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { search } from '../sagas/search';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import Toggle from 'material-ui/Toggle';
import InputSearch from '../components/InputSearch/InputSearch';
const resetSearchMock = jest.fn();
const searchBooksMock = jest.fn();
const toggleResultsOpacityMock = jest.fn();
const muiTheme = getMuiTheme();
const props = {
keyword: '',
resetSearch: resetSearchMock,
searchBooks: searchBooksMock,
toggleResultsOpacity: toggleResultsOpacityMock,
firstSearch: true,
};
const setup = () => {
const wrapper = mount(
<InputSearch {...props} />,
{
context: {muiTheme},
childContextTypes: {muiTheme: React.PropTypes.object}
}
);
return {
props,
wrapper,
};
};
const { wrapper } = setup();
const textFieldMUI = wrapper.find(TextField);
const toggleAuthor = wrapper.find(Toggle).find('input#author');
const toggleTitle = wrapper.find(Toggle).find('input#title');
const button = wrapper.find(RaisedButton).find('button');
describe ('Initial test, validate fields', () => {
test('TextField component should exists.', () => {
expect(textFieldMUI).toBeDefined();
});
test('Shows an error message when input search is empty and the search button is clicked.', () => {
const { props } = setup();
props.keyword = '';
const wrapper = mount(
<InputSearch {...props} />,
{
context: {muiTheme},
childContextTypes: {muiTheme: React.PropTypes.object}
}
);
button.simulate('click');
expect(textFieldMUI.props().errorText).toEqual('This field is required');
});
test('Shows an error message when both "author" and "title" toggles are off and the search button is clicked.', () => {
toggleTitle.simulate('click');
button.simulate('click');
expect(textFieldMUI.props().errorText).toEqual('Select at least one filter (Title or Author)');
});
});
Enzyme shallow renders only one level deep, so in your case only MuiThemeProvider and InputSearch are rendered. You can use Jest snapshot feature to see what was rendered inside wrapper. You can use dive to force Enzyme to render the content of a component:
expect(wrapper.('InputSearch').dive().find(TextField).getValue()).toEqual('');
or you dont wrap the component with MuiThemeProvider and render InputSearch directly. You only need to add the styles prop. Now InputSearch is the top level component and Enzyme will render its content.
const setup = () => {
const props = {
keyword: '',
resetSearch: resetSearchMock,
searchBooks: searchBooksMock,
toggleResultsOpacity: toggleResultsOpacityMock,
firstSearch: true,
styles: {textfield: {fontSize:10}}
};
const wrapper = shallow(<InputSearch {...props} />);
return {
props,
wrapper,
};
};
const event = { 'target': { 'value': 'No' } };
wrapper.find('#selectBox').prop('onChange').call(null, event);

Resources