Using basic test-utils and jasmine for unit testing.
How do you spy on a function inside a react component?
test.js:
class Test extends React.Component {
handleClick() {
// Do something
}
render() {
return (
<div className="test-class" onClick={this.handleClick}>Test</div>
);
}
}
const React = require('react-with-addons');
const RequireJsTest = require('requirejs-test');
const Utils = React.addons.TestUtils;
const Test = require('./test');
describe('test', () => {
it('should test', function() {
const test = Utils.renderIntoDocument(<Test/>);
const el = Utils.findRenderedDOMComponentWithClass(test, 'test-class');
spyOn(test, 'handleClick');
Utils.Simulate.click(el);
expect(test.handleClick).toHaveBeenCalled();
});
});
I'm getting the following error:
Expected spy handleClick to have been called. (1)
Any ideas? Thanks!
To be honest, I haven't tested react apps yet, but try the method (the last test in describe block), which I've just found in enzyme readme doc.
I think you should spy on component class prototype method before rendering component:
spyOn(Test.prototype, 'handleClick');
// and then
expect(Test.prototype.handleClick).toHaveBeenCalled();
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