Reputation: 7107
I'm writing a web application using react
. I am not very familiar with client tests, so I'm still trying to figure out how to unit test my components.
I have seen in react
docs that they offer the Test Utilities
to test custom UI components, but I didn't find a way to test functions inside my component.
I have a form in which I want to validate the fields, lets say validate the email address. How can I test the functionality of this method? From what I have seen, people just test the UI component itself.
Upvotes: 2
Views: 471
Reputation: 5533
It's a bit convoluted, but here's an example that uses skin-deep to test functions inside a react component.
Component file:
export default React.createClass({
validate(input) {
return true
},
render() {
if (validate(this.props.input)) {
return <div>Valid!</div>
}
return <div>Not Valid!</div>
}
})
Test file:
import React from 'react'
import sd from 'skin-deep'
import Component from 'Component.jsx'
let tree = sd.shallowRender(React.createElement(Component, {}))
const instance = tree.getMountedInstance()
// Now you can run tests on instance functions.
assert instance.validate(foo) === true
We've been putting functions we want to test outside of the React components to avoid doing this.
Upvotes: 4