toEqualJSX for mjackson/expect.
It uses algolia/react-element-to-jsx-string in the background to turn React elements into formatted strings.
Table of Contents generated with DocToc
You will most probably use this plugin as a development dependency.
npm install expect-jsx --save-dev
- expect(ReactComponent|JSX).toEqualJSX(ReactComponent|JSX)
- expect(ReactComponent|JSX).toNotEqualJSX(ReactComponent|JSX)
- expect(ReactComponent|JSX).toIncludeJSX(ReactComponent|JSX)
- expect(ReactComponent|JSX).toNotIncludeJSX(ReactComponent|JSX)
Here's an example using mochajs/mocha.
import React from 'react';
import expect from 'expect';
import expectJSX from 'expect-jsx';
expect.extend(expectJSX);
class TestComponent extends React.Component {}
describe('expect-jsx', () => {
it('works', () => {
expect(<div />).toEqualJSX(<div />);
// ok
expect(<div a="1" b="2" />).toEqualJSX(<div />);
// Error: Expected '<div\n a="1"\n b="2"\n/>' to equal '<div />'
expect(<span />).toNotEqualJSX(<div/>);
// ok
expect(<div><TestComponent /></div>).toIncludeJSX(<TestComponent />);
// ok
});
});
It looks like this when ran:
toEqualJSX
will not check for function references, it only checks that if a function
was
expected somewhere, there's also a function in the actual data.
It's your responsibility to then unit test those functions.
npm test
npm run test:watch
npm run build
npm run build:watch
There are multiple similar projects for other assertions libraries, all based on algolia/react-element-to-jsx-string. For instance:
- chai-equal-jsx, assertions for chai:
expect(<div />).to.equalJSX(<div />);
- chai-jsx, assertions for chai:
expect(<div />).jsx.to.equal(<div />);
- jsx-chai, assertions for chai:
expect(<div />).to.deep.equal(<div />);
- tape-jsx-equals, assertions for tape:
t.jsxEquals(<div />, <div />);
To the people pointing me in the right directions like: