1
votes

So am I testing React app with Mocha+Enzyme+Sinon. I am trying to test a function with if statement in which there is a call to another function. My goal is to enter the if statement, but stub the second function call. Here is the code:

    onSearchChange = ({value}) => {
    const port = '/search-users?search_q=';
    const path = [port, value].join('');

    if (value.length >= 2 && value.length <= 5) {
        this.getUsers(path, (array) => {
            this.setState({ suggestions: fromJS(array) })
        });
    }
};

So I want to enter if statement, but not call getUsers() function. How can I do that? I am spying onSearchChange() like this:

const wrapper = shallow(<ContentEditor />);
const spy = sinon.spy(wrapper.instance(), 'onSearchChange');

Looking forward to hear, thanks!

1
You should never mock or stub methods on the object you test. In your case I assume that getUser makes some ajax request, so stub the thing that make the request instead of manipulating your tested class. - Andreas Köberle

1 Answers

0
votes

i think we can stub the function inside the component you are testing this way.

sinon.stub(ContentEditor.prototype, 'getUsers')

and test it like

expect(ContentEditor.prototype.getUsers.called).to.be.true;