mount() fails because target container is not dom element - reactjs

I'm getting error message Target container is not a DOM element. Using webpack.
Full Error:
FAIL src/App.test.js
● Test suite failed to run
Invariant Violation: Target container is not a DOM element.
at invariant (node_modules/fbjs/lib/invariant.js:42:15)
at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:17238:34)
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:17317:12)
at Object.<anonymous> (src/index.js:32:20)
at Object.<anonymous> (src/App.test.js:5:14)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:169:7)
App.js
import React, { Component } from 'react';
import './App.scss';
import Tables from './containers/Tables/Tables'
class App extends Component {
render() {
return (
<Tables />
);
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { combineReducers, createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import aaaApi from '#aaa/aaajs';
import './index.css';
import App from './App';
import tableBuilderReducer from './store/reducers/tableBuilder'
import registerServiceWorker from './registerServiceWorker';
const aaa = new aaaApi('xxx');
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const reducers = {
platforms: tableBuilderReducer('platforms'),
regions: tableBuilderReducer('regions'),
playback: tableBuilderReducer('playback')}
export const store = createStore(
combineReducers(reducers),
composeEnhancers(
applyMiddleware(thunk.withExtraArgument(aaa)),
),
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
registerServiceWorker();
App.test.js
import React from 'react'
import Enzyme, { mount, shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import App from './App'
import { store } from './index.js'
Enzyme.configure({ adapter: new Adapter() })
function setup() {
const props = {
sortColumnHandler: jest.fn()
}
const enzymeWraper = mount(<App />)
return {
props,
enzymeWraper
}
}
describe('components', ()=> {
describe('Tables', () => {
it('should render self and sub-components', () => {
const { enzymeWraper } = setup()
})
})
})

The issue is being caused by index.js being included in the test and is failing at ReactDOM.render() when root is not found in the document created by the jsdom environment in Jest.
import { store } from './index.js' is not needed in App.test.js so removing that will fix the initial error.
Using mount from enzyme does a full DOM rendering and requires that everything be set up for a full render. It should only be used to unit test components that use lifecycle methods, interact with the DOM, etc. It will fully render the component being tested and all children components. In this case the children of App use the redux store so a store would need to be provided in a wrapping Provider in order to do a full render using mount.
In most cases, React components should be unit tested using shallow. It does a shallow rendering of just the component being tested. In this case App is a simple stateless component that contains Tables so using shallow is the right approach.
bonus tip:
Install enzyme-to-json as a dev dependency, add it to Jest as a snapshot serializer, and App.test.js gets simplified to this:
import { shallow } from 'enzyme';
import * as React from 'react';
describe("App", () => {
it('renders as expected', () => {
const component = shallow(<App />);
expect(component).toMatchSnapshot();
});
});

Related

Unit testing Chakra UI with Jest

Currently I am trying to unit test my application that is built with Create-React-App with typescript, and it is styled with chakraui. Chakrui includes a component ThemeProvider that must wrap the entire application as such.
This is my index.tsx file
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { ThemeProvider, CSSReset } from "#chakra-ui/core/dist";
import { theme } from "#chakra-ui/core/dist";
ReactDOM.render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<CSSReset />
<App />
</ThemeProvider>
</React.StrictMode>,
document.getElementById("root")
For every unit test that I write, I am having to wrap the component with ThemeProvider for the test to pass:
import React from "react";
import { render } from "#testing-library/react";
import { ThemeProvider } from "#chakra-ui/core/dist";
import App from "./App";
describe("<App />", () => {
test("smoke test", () => {
render(
<ThemeProvider>
<App />
</ThemeProvider>
);
});
});
But this is very verbose, and must be done for every test that I write. Is there a way to do this just once in each .test.tsx file?
You could create your own theme wrapper function
import React from "react";
import { ThemeProvider } from "#chakra-ui/core/dist";
export const ThemeWrapper = ({ children }) => (
<ThemeProvider>{children}</ThemeProvider>
);
And then specify the wrapper in the test
import React from "react";
import { render } from "#testing-library/react";
import { ThemeWrapper } from "../testUtils";
import App from "./App";
describe("<App />", () => {
test("smoke test", () => {
render(<App />, { wrapper: ThemeWrapper });
});
});
This marginally reduces the code for testing. You may be able to also go the route of creating a custom render function (following the steps for redux).
It could look something like
import React from "react";
import { render } from "#testing-library/react";
import { ThemeProvider } from "#chakra-ui/core/dist";
export const renderWithTheme = ui => {
const Wrapper = ({ children }) => (
<ThemeProvider>{children}</ThemeProvider>
);
return render(ui, { wrapper: Wrapper });
};
Basically the same as the wrapper above, but more integrated into a test render function. You can adjust the function signature a bit as well if you need to pass in a theme object, or other render options, this is just a simple example.
Now the test looks like
import React from "react";
import { renderWithTheme } from "../testUtils";
import App from "./App";
describe("<App />", () => {
test("smoke test", () => {
renderWithTheme(<App />);
});
It might be the case that Jest might be mocking your imports from #chakra-ui/core/dist (depending on your jest configuration) which might be resulting your imported chakra-ui components to be undefined.
Importing the Theme Provider and wrapping it everytime with your renders might be one way to do it. The problem might arise when you have multiple components in your index.tsx. So, you might not want to import each and every component.
In that case, you will want to import the actual components from #chakra-ui/core.
The best way (according to me) to do so in Jest is:
jest.mock("#chakra-ui/core", () => {
const ui = jest.requireActual("#chakra-ui/core");
return {
...ui,
customKey: 'customValue',
};
})
This way you can even add custom function and key-values to the imported module.

Client.abort is not a function

I am getting below error while run test cases by using jest with react testing library
import React from 'react';
import { render} from '#testing-library/react';
import Somecomponent from './Somecomponent';
import { Provider } from 'react-redux';
import store from './store';
describe('<Somecomponent /> spec', () => {
it('renders the component', () => {
const container = render(
<Provider store={store}>
<Somecomponent />
</Provider>
);
expect(container.firstChild).toMatchSnapshot();
});
});
Actual Result:
Test suite failed to run
TypeError: client.abort is not a function
at XMLHttpRequest.abort (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:379:16)
at Object.abort (node_modules/jsdom/lib/jsdom/living/xhr-utils.js:425:13)
at RequestManager.close (node_modules/jsdom/lib/jsdom/living/nodes/Document-impl.js:133:21)
at Window.close (node_modules/jsdom/lib/jsdom/browser/Window.js:513:29)
I might be a little late to the party, but I found my solution here (in my case the error also occurred in Angular application). Adding the HttpClientTestingModule ensures it's not doing actual http requests in test cases.

Testing in React Redux

I have Dashboard component like below.
import React, { Component } from 'react';
import DataTable from './DataTable';
import { connect } from 'react-redux';
class Dashboard extends Component {
render() {
return <DataTable />;
}
}
export default connect()(Dashboard);
My test is like below
App.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import Dashboard from './components/Dashboard';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Dashboard />, div);
ReactDOM.unmountComponentAtNode(div);
});
describe('Addition', () => {
it('knows that 2 and 2 make 4', () => {
expect(2 + 2).toBe(4);
});
});
I am trying to run test using this command npm test App.test.js.
I am getting below error
Invariant Violation: Could not find "store" in the context of "Connect(Dashboard)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Dashboard) in connect options.
Your Dashboard is connected to redux, which requires a store. You have a two possibilities :
use Enzyme and redux-mock-store in order to configure a store used when you're mounting your component. This is not well maintainable and leads to a strong dependency between Component and store.
export the non-connected Dashboard (in addition to the default export connected), and mount (eventually with the required props). This is much simpler and maintainable.
export class Dashboard extends Component {
render() {
return <DataTable />;
}
}
// Test :
import { Dashboard } from './components/Dashboard';
ReactDOM.render(<Dashboard />, div);
Note: I think you simplified your connect() for the example purpose, because it does not do anything here, but if this is your real implementation you could drop the connect part and still use the default export for your test.

How to handle two configureStore files for Redux in TypeScript (multiple module.exports)?

I'm building a React Native app with TypeScript using Redux for my state.
I like using two seperate files for configureStore. In JS This looks like this:
configureStore.dev.js:
import { applyMiddleware, createStore } from "redux";
import logger from "redux-logger";
import reducers from "../reducers";
const configureStore = () => {
const store = createStore(reducers, applyMiddleware(logger));
return store;
};
export default configureStore;
configureStore.prod.js:
import { createStore } from "redux";
import reducers from "../reducers";
const configureStore = () => {
const store = createStore(reducers);
return store;
};
export default configureStore;
configureStore.js:
import Config from "react-native-config";
if (Config.REACT_ENVIRONMENT === "staging") {
module.exports = require("./configureStore.dev");
} else {
// tslint:disable-next-line no-var-requires
module.exports = require("./configureStore.prod");
}
And then within App.js:
import React, { Component } from "react";
import Orientation from "react-native-orientation";
import { Provider } from "react-redux";
import Navigator from "./navigation/Navigator";
import configureStore from "./redux/store/configureStore";
export const store = configureStore();
export default class App extends Component {
componentDidMount = () => {
Orientation.lockToPortrait();
};
render() {
return (
<Provider store={store}>
<Navigator />;
</Provider>
);
}
}
The problem now with TypeScript is that - after converting these files to .ts and .tsx - this code throws linting errors (and it furthermore blocks all Jest unit tests from running).
The lines where modules.exports exports the respective file depending on environment variables throws the error:
[tslint] require statement not part of an import statement (no-var-requires)
And in App.tsx the import of configureStore throws:
[ts] Module '"/Users/jan/Documents/FullStackFounders/PainButton/painbutton/app/redux/store/configureStore"' has no default export.
How would one handle this case in TypeScript?
The only solution I could come up with was only using one file and using a lot of if's for all the Dev only configs. But that doesn't seem clean to me.
It seems you are mixing import / export and require / module.exports syntax.
Try to use dynamic import expressions.
configureStore.js
export default Config.REACT_ENVIRONMENT === "staging" ? import("./configureStore.dev") : import("./configureStore.prod");
main render file
import configure from "./configureStore.js";
configure.then(configFunc => {
const store = configFunc();
ReactDOM.render(<App store={store} />, document.querySelector("#root"));
})
Pass the store as a prop to the <App /> Component.
I hope it will help.

Test a create-react-app index.js file

I would like to have 100% coverage on my project.
In order to do so, I need to test my index.js file which is very basic :
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<App/>, document.getElementById('root'));
I can't find how to test this.
When creating a function such as :
index.js
const index = (div) => {
ReactDOM.render(<App />, div || document.getElementById('root'));
};
and then testing it :
index.test.js
it('renders without crashing', () => {
const div = document.createElement('div');
index(div);
});
I get an error when importing index:
Invariant Violation: _registerComponent(...): Target container is not a DOM element.
PS:
Note that I already have the following test, working perfectly :
App.test.jsx
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App/>, div);
});
If 100% coverage on your project is your goal and the code in your index.js file is trivial, then it might be a good option to exclude the file from the coverage report, as Andreas Köberle points out in his answer.
Create-react-app currently only supports these four keys in the Jest configuration (source):
collectCoverageFrom
coverageReporters
coverageThreshold
snapshotSerializers
This is why
coveragePathIgnorePatterns": ["src/index.js"]
won't work.
Add following code to the most outer scope of your package.json file:
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!src/index.js"
]
}
In the image below you see the output of a test run with this code added to the package.json of the initial app created with create-react-app v1.4.3. Note that the index.js file doesn't show up in the report anymore and also doesn't affect the coverage percentage.
This is how I've tested index.js
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
index.test.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
jest.mock("react-dom", () => ({ render: jest.fn() }));
describe("Application root", () => {
it("should render without crashing", () => {
const div = document.createElement("div");
div.id = "root";
document.body.appendChild(div);
require("./index.js");
expect(ReactDOM.render).toHaveBeenCalledWith(<App />, div);
});
});
The main question is what you want to test there. If you want to test that your code works correct, write a unit test that spies on ReactDOM.render and mocks document.getElementById('root'). Cause this is all your code does, calling ReactDOM.render with our App component and a specific div.
import ReactDOM from 'react-dom';
...
jest.mock('react-dom', ()=> ({render: jest.fn()}))
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App/>, div);
global.document.getElementById = (id) => id ==='root' && div
expect(ReactDOM.render).toHaveBeenCalledWith(...)
});
If you want test that the app really starts in your page, you should write integration test with Selenium or Nightwatch.js
To just get 100% coverage you can also ignore this file by adding it to the coveragePathIgnorePatterns in your jest settings
I found an article online that explains this way to write the test...
// index.test.js
import Index from './index.js';
it('renders without crashing', () => {
expect(JSON.stringify(
Object.assign({}, Index, { _reactInternalInstance: 'censored' })
)).toMatchSnapshot();
});
Now change the index.js file accordingly:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
export default ReactDOM.render(
<App />,
document.getElementById('root') || document.createElement('div')
);
Extending on dcastil's answer, here's how to skip these trivial files for a TypeScript project:
Edit package.json
At the root level add the following snippet
{
...rest of existing props,
"jest": {
"collectCoverageFrom": [
"src/**/*.{ts,tsx}",
"!src/serviceWorker.ts",
"!src/index.tsx"
]
}
}
Save and re-run coverage
By now coverage should be higher.
Inspired by the answer above by Shiraz. This is essentially the same solution but for React 17/18. Also it provides some additional test coverage.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode />,
);
import React from 'react';
import ReactDOM from 'react-dom';
const render= jest.fn().mockName('render');
jest.mock('react');
jest.mock('react-dom', () => ({
createRoot: jest.fn().mockName('createRoot')
}));
let documentSpy=jest.spyOn(document, 'getElementById')
describe('Entry point index test', () => {
const doc =document.createElement('div');
doc.setAttribute('id', 'root');
beforeEach(() => {
ReactDOM.createRoot.mockReturnValue({render});
require("../index.js");
});
it('should call ReactDOM.createRoot once', () => {
expect(ReactDOM.createRoot).toHaveBeenCalledTimes(1);
});
it('should call document.getElementById with root once', () => {
expect(documentSpy).toHaveBeenCalledTimes(1);
expect(documentSpy).toHaveBeenCalledWith('root');
});
it('should call render with React.StrictMode', () => {
expect(render).toHaveBeenCalledTimes(1);
expect(render).toHaveBeenCalledWith( <React.StrictMode />,);
});
});
Here what i did and looks like it works just perfect (100% coverage, app doesn't break):
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
export const ReactStrictMode = <React.StrictMode>
<App />
</React.StrictMode>
export const rootElement = document.getElementById('root')
ReactDOM.render(
ReactStrictMode,
rootElement
);
and then in index.spec.js:
// src/index.spec.js
/* eslint-env jest */
import React from 'react'
import ReactDOM from 'react-dom'
import { ReactStrictMode, rootElement } from './index'
jest.mock('react-dom', () => ({ render: jest.fn() }))
describe('index.js', () => {
it('renders without crashing', () => {
ReactDOM.render(ReactStrictMode, rootElement)
expect(ReactDOM.render).toHaveBeenCalledWith(ReactStrictMode, rootElement)
})
})
Added a couple of more test cases. Any feedback would be appreciated...
import React from "react";
import { render, cleanup } from "#testing-library/react";
import ReactDOM from "react-dom";
import App from "./App";
afterEach(cleanup);
// jest.mock will mock all the function using jest.fn() that is present inside the react-dom library
jest.mock("react-dom");
describe("Testing Application Root", () => {
it("should render without crashing", () => {
const div = document.createElement("div");
div.id = "root";
document.body.appendChild(div);
require("./index");
expect(ReactDOM.render).toHaveBeenCalledWith(<App />, div);
});
it("should render the app inside div which has root id", () => {
expect(global.document.getElementById("root")).toBeDefined();
});
it("should render App component", () => {
expect(App).toBeDefined();
});
});

Resources