Skip to content

Instantly share code, notes, and snippets.

@andy-polhill
Last active November 2, 2015 08:56
Show Gist options
  • Save andy-polhill/e629a7954789cdd2ad71 to your computer and use it in GitHub Desktop.
Save andy-polhill/e629a7954789cdd2ad71 to your computer and use it in GitHub Desktop.
Why we need to be able to call a component instance method on some occasions during test
import React, {Component} from 'react';
import Child from './Child'
class Example extends Component {
a() {
//do some stuff
this.c();
}
b() {
//do some different stuff
this.c()
}
c() {
//do some common stuff
}
render() {
return(
<div>
<Child doA={this.a.bind(this)} doB={this.b.bind(this)} />
</div>
)
}
}
}
import Child from './Child'
import Example from './Example'
describe('Example', () => {
describe('a', () => {
it('should do some stuff', () => {
component = createComponent.interleaved(<Example />);
child = component.findByComponent(Child)[0];
assert(child.props.doA())
});
});
describe('b', () => {
it('should do some different stuff', () => {
component = createComponent.interleaved(<Example />);
child = component.findByComponent(Child)[0];
assert(child.props.doB())
});
});
describe('c', () => {
it('should do some common stuff', () => {
component = createComponent.interleaved(<Example />);
//FIXME How do I test 'C' without first calling 'A' or 'B'
})
});
})
@andy-polhill
Copy link
Author

I think this is a scenario where we may need to have access to the instance methods of the component. Otherwise we cant test method c without first calling a or b.

@kamilio
Copy link

kamilio commented Oct 30, 2015

Utils!

@andy-polhill
Copy link
Author

Utils would work if c was static.

@andy-polhill
Copy link
Author

Putting it into a real life context..

  focusOnInput() { //c
    this.setState({ inputFocused: true });
  }

  searchAddTerm(term)  { //a
    this.props.searchActions.searchAddTerm(term);
    this.focusOnInput();
  }

  searchRemoveTerm(term)  { //b
    this.props.searchActions.searchRemoveTerm(term);
    this.focusOnInput();
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment