With the simplest ReactJS component Jest is not reporting full test coverage. How to get statements and branch to show 100%.
Currently Jest shows 90.48% statements, 58.06% branch
.
Run with jest --coverage
.
MyThing.js
import React from 'react';
export default class MyThing extends React.Component {
render() {
return (
<div>
Stuff
</div>
);
}
}
MyThing-test.js
// __tests__/MyThing-test.js
jest.unmock('../app/views/static/MyThing');
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import MyThing from '../app/views/static/MyThing';
describe('MyThing', () => {
const instance = TestUtils.renderIntoDocument(
<MyThing />
);
it('gets rendered', () => {
expect( TestUtils.isCompositeComponent(instance) ).toBeTruthy();
});
it('is not DOM component', () => {
// checks if is a standard DOM element, i.e. <div>
expect( TestUtils.isDOMComponent(instance) ).not.toEqual(true);
});
it('isElementOfType is React element', () => {
expect( TestUtils.isElementOfType(<MyThing />, MyThing) ).toEqual(true);
});
it('render()', () => {
const retVal = instance.render();
expect( retVal.type ).toEqual("div");
});
});
Test With Shallow, Mount, or Render There are three ways to load a React component with Enzyme: shallow(<Component />) : It tests components in isolation from the child components they render. mount(<Component />) : It tests components as well as their children. It enables testing the full lifecycle of components.
Make sure to include a screenshot of a coverage report with a lot of green stuff in your PowerPoint presentation. Another great trick is to exclude untested code from coverage calculations. Jest is an amazing tool that does it by default for JS — only the code that is imported in your tests takes is taken into account.
But to get branch coverage of 100% you need to make that if is not running for some specific test case. hasOwnProperty returns false for properties inherited from prototype. So we will use that to make that line is not executed: const base = { a: 1}; const source = Object.
This is most likely due to the transpiled code from babel. See issue #817 where this issue was worked on and just recently resolved.
This should be fixed with the upgrade to jest@15
.
Though some people mentioned the need to add sourcemaps to their .babelrc
such as:
{
"env": {
"test": {
"sourceMaps": "both"
}
}
}
and update their jest to explicitly with "coverageCollector": "jest-babel-istanbul"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With