score:2
here's a simple example for unit testing react components using mocha, chai, and a jsdom helper, which is used in place of a test runner like karma.
you will need the following dependencies:
"dependencies": {
"react": "^15.1.0",
"react-dom": "^15.1.0"
},
"devdependencies": {
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"babel-register": "^6.9.0",
"chai": "^3.5.0",
"jsdom": "^9.3.0",
"mocha": "^2.5.3"
}
it's also useful to have an npm script that points to mocha - npm run test
will execute your tests:
"scripts": {
"test": "./node_modules/.bin/mocha"
},
after you have your dependencies set up, you'll want a directory structure that looks like this:
.
├── /src
│ └── component-to-test.js
├── /test
│ ├── /unit
│ │ └── component-to-test.spec.js
│ ├── /util
│ │ └── jsdom.js
│ └── mocha.opts
├── .babelrc
└── package.json
we'll start off with your .babelrc
file. you'll need babel to transpile your jsx into javascript. if you want to use es6 syntax (highly recommended), babel will help with that too. i've included both of these presets in the devdependencies.
.babelrc:
{
"presets": ["es2015", "react"]
}
next, we'll look at the jsdom helper. this is needed in order to render react components into an in-memory dom, which is typically handled by a test runner like karma.
jsdom.js:
(function () {
'use strict';
var jsdom = require('jsdom'),
basehtml,
window;
if (!global.window) {
basehtml = '<!doctype html><html><head lang="en"><meta charset="utf-8"><title>tests</title></head><body></body></html>';
window = jsdom.jsdom(basehtml).defaultview;
global.window = window;
global.document = window.document;
global.navigator = window.navigator;
}
}());
in order to leverage this jsdom helper for use in our mocha tests, we'll need to set up a mocha.opts
file that specifies a few configuration options. we'll add a compiler that will tell babel to pre-process the tests, and we'll require
the jsdom helper so react has a dom to use to render components.
mocha.opts:
--compilers js:babel-register
--recursive
--reporter spec
--ui bdd
--require ./test/util/jsdom.js
finally, we can start testing react components. as an example, here is a simple component that we can test.
test-component.js:
import react from 'react';
export default class testcomponent extends react.component {
render() {
return (
<div classname="test-component">here is a test component</div>
);
}
}
and here is a test suite that will test this component's markup.
test-component.spec.js:
import testcomponent from '../../src/test-component';
import {expect} from 'chai';
import react from 'react';
import reactdom from 'react-dom';
import reacttestutils from '../../node_modules/react/lib/reacttestutils';
describe('test component', () => {
let renderednode;
function rendercomponent() {
const componentelement = react.createelement(testcomponent),
renderedelement = reacttestutils.renderintodocument(componentelement);
renderednode = reactdom.finddomnode(renderedelement);
}
beforeeach(() => {
rendercomponent();
});
it('should exist with the correct markup', () => {
expect(renderednode.tagname).to.equal('div');
expect(renderednode.classname).to.equal('test-component');
expect(renderednode.textcontent).to.equal('here is a test component');
});
});
at this point, the command npm run test
should result in a single passing test.
and that's it! if you're looking for more advanced testing techniques, you can completely avoid the need for a jsdom helper and use shallow rendering for your tests. i highly recommend enzyme if you want to take this approach.
let me know if you have any questions!
Source: stackoverflow.com
Related Query
- Testing React components with a .jsx extension
- Nested components testing with Enzyme inside of React & Redux
- Do I have to save react component files with a jsx extension
- How to test components internal functions with React testing library
- Testing Webpack built React components with Jest
- Unit testing ES7 React components with Jest
- Getting started testing React components with Enzyme and Jest
- Testing components that contain react router Link with Enzyme
- Testing React components with Mocha: unexpected token
- How to mock react components with react testing library?
- Error when testing react components with jest and css-modules
- How to resolve "Cannot find module" Error when testing react components with mocha
- Testing complex React components with Mocha/Chai
- How to Test Responsive React Components with React Testing Library
- Testing components using react testing library with AuthContext
- React Passing Data to Components with JSX vs Native Javascript
- Very high memory/cpu usage while testing React components with Karma in Chrome
- Testing react components that have JSS injected styles with enzyme
- Testing react components with PropTypes
- Testing nested JSX with React Testing Library
- Testing React Components with asynchronous methods
- Error creating React components with map() without JSX
- Testing react components with redux-toolkit inside
- React JSX - Do we have any cli that supports components creation with .jsx file extension?
- Testing React components with Enzyme when component uses events
- Mapping components with variable props not rendering from JSX to DOM, React
- Testing React components with Jest & Enzyme: where to test whether component props were given
- React Jest to match snapshot, crash when testing component with child components
- Unit Testing with Mocha,Enzyme dispatched functions in functional components which uses React Hooks + Redux
- Components overlapping in page render with react jsx
More Query from same tag
- How to append multiple values in setstate for array object Reactjs
- React - parent class component function change class of child component
- useState variable not getting passed through props
- Change color of the IconComponent of Material UI's Select Component
- Time isn't showing correctly in React. How can I get rid of the PM or format it so that it doesn't show there?
- Appending a key value pair to an array of dictionary based on a condition javascript
- Map data to display 2 attributes
- Inserting values inside an array which is in an State - React
- How can I interpolate a Animated value to result into a boolean or a string in react-native?
- Uncaught TypeError: Cannot read property 'files' of undefined
- Strange behaviour in <header> tag in Meteor + React
- React force componentDidMount
- How do I make containers that trisects a page vertically in ant design?
- Unexpected token, expected ";" at render ()
- how to check if object.values in array are the same in sequence
- How to Change the Color of the typography with a certain condition
- Struggling to display Smart Contract information in web page using react.js
- How to send files from client to http node server
- React add property to immutable object
- React.js onClick event returning all null values
- Json response returning HTML in nodejs/react page
- OnClick fires for another buttons click event
- React change file without rebuild and restart
- Calculate the percentage of an object property
- Node keeps sending GET /sockjs-node/info requests after terminating with CTRL + C
- Google Sign In within embedded browsers (Messenger, Instagram) not working.. Googles webview policy?
- Detect Firebase Realtime Change For Specific User
- CORS error using passport-azure-ad on React + Express app
- Returning Null When Fetching API Asynchronously Before Data Fetches
- How can I add checkbox values to setState array in reactJS