Below I have an example React component that behaves as follows -
- When the
showDivstate isfalse(initial state), it renders nothing. - When the
showDivstate is updated totrue(maybe by some external component, redux, etc..), it renders a<div>with a single radio input.
I've also included Jest tests:
import { expect } from 'chai';
import { mount } from 'enzyme';
import PropTypes from 'prop-types';
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { showDiv: false };
}
render() {
const { showDiv } = this.state;
if (!showDiv) { return null; }
return (
<div className='my-component'>
<input type="radio" value="yes" id="foo" checked={true} />
</div>
);
}
}
describe('<MyComponent />', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(<MyComponent />);
});
it('should render the div', () => {
// This INCORRECTLY passes
expect(wrapper.find('#foo').at(0)).to.not.be.null;
expect(wrapper.find('#foo').at(0)).to.be.checked;
});
});
I wrote the test to verify that the <input> exists and that it is checked, and the test passes.
However, on initial component mount/load that <input> should not be rendered (since showDiv is false), so why is the test passing?
I even output the state of the component with console.log(wrapper.find('#foo').at(0).debug()); and I can verify that nothing is being rendered... but it still passes.
$ npx jest --no-cache --config test/js/jest.config.js test/js/components/test.spec.jsx
● Console
console.log test/js/components/test.spec.jsx:34
Any reason why this gives a false positive? Specifically, why the find() returns elements that don't exist, but still pass the checks (e.g. .to.be.checked)