I'm really, really lost.
I'm trying to keep my React app simple. I don't feel we need Redux based on the scope of the app. Yet when it comes to testing, it seems like I have to jump through so many hoops to get good coverage. It seems so ridiculous, that I must have it wrong in my head. Please, help?
For example,
class LoginForm extends Component {...}
onHandleClick(e) {
if (this.state.username === '' && this.state.password === '') {
this.setState({ error: 'Invalid details', });
} else {
this.setState({ error: '', });
}
}
I want to write a test that makes sure the state.error is set to 'Invalid details' when the credentials are blank. I should be able to mount the component and access its instance().onHandleClick() - I think?
Except, it won't let me mount it directly, because I need to wrap it in a MemoryRouter because the LoginForm does redirect based on credentials being correct.
Of course, I can
mount(<MemoryRouter><LoginForm /></MemoryRouter>);
...but then I can't access the wrapper's instance().onHandleClick() anymore because MemoryRouter doesn't have the method, it's within a child.
It seems like the testing would be 100x easier if none of my components had any idea what their methods did, it was all passed through in props, and my tests mocked up every function... but then, cringe, how would I know that the ACTUAL methods worked if I was using mock methods to test all my components?
You take it far enough and Redux seems like the only choice... but I have a really, really simple CRUD app and I don't want to over complicate it, I just want to be able to test my components!
Please help.
IMHO you should use Sinon
http://sinonjs.org/
to test that sort of thing, here is an article about it.
http://engineering.pivotal.io/post/stub-dont-shallow-render-your-child-components/
But basically solution should be somwhere between stub()
and spy()
from sinon.
If you want to test get dipper into testing check out JEST
it is great testing tool that is based on snapshoots so you simply compare rendered code with the code that suppose to be. It is also recomended by Facebook.