Ria Ria - 2 months ago 15x
Javascript Question

How to mock an instance created in React JS component?

I'm trying to mock an instance which is created in a React JS component.
The instance is a common ECMAScript 2016 class, not a React component. I use Jasmine, React JS TestUtils and babel-rewire for testing.

My React component code looks like this:

import MyHandler from '../../js/MyHandler';
export default class MyComponent extends React.Component {

constructor(props) {
this.myHandler = new MyHandler();

someComponentMethod() {

render() {
return <div>...</div>;

My class looks like this:

export default class MyHandler {

someMethod() {
// ...

My test and what I tried so far:

// gives exception
let myHandler = new MyHandler();
let spy = spyOn(myHandler, "someMethod").and.returnValue(null);
MyComponent.__Rewire__ ("MyHandler", spy);
// also gives exeption
MyComponent.__set__ ("MyHandler", spy);

let component = TestUtils.renderIntoDocument(<MyComponent />);

For mocking other React components I use
which works great. But I can't replace the instance by a mock or spy.

I know I could pass the instace into the component as a property (and thus mock it in a test), but I wonder if this is good practise and I'm afraid I'll have the problem in the next coomponent .

Any help appreciated!


You could use the injector loader something along these lines

const MyComponentInjector = require('inject!'MyComponent');
MyComponent = MyComponentInjector({
  '../../js/MyHandler': YourMockedClass

that would provide a MyComponent with YourMockedClass as Mock for your handler