2
votes

Trying to test React component, using Karma+Jasmine, I'm trying to check that all function into onClick handler is invoked, but the test return false result:

`Expected spy reportLoginWithEmail to have been called.`

Here is my component:

<a className="sign-in-with-email" onClick={this.signInWithEmail}>
   Or Sign in with your Email
</a>

signInWithEmail handler:

signInWithEmail = (event) => {
  event.preventDefault();
  this.setState({
    isEmailSignIn: true
  });
  biActions.reportLoginWithEmail(); 
};

Test:

  describe('SignIn', () => {
  let component, biActions;

  beforeEach(() => {
    component = TestUtils.renderIntoDocument(<SignIn/>);
    biActions = require('../../../actions/BIActions');

    spyOn(biActions, 'reportLoginWithEmail');
  });

  it('test clicking on login by email call function', () => {
    let signInEmail =       TestUtils.findRenderedDOMComponentWithClass(component, 'sign-in-with-email');
    TestUtils.Simulate.click(signInEmail);
    expect(biActions.reportLoginWithEmail).toHaveBeenCalled();
  });

});

On another side the test of state change return true :

it('test clicking on login by email change state', () => {
    let signInEmail = TestUtils.findRenderedDOMComponentWithClass(component, 'sign-in-with-email');
    TestUtils.Simulate.click(signInEmail);
    expect(component.state.isEmailSignIn).toBe(true);
  });

What am I missing, any suggestions?

1

1 Answers

1
votes

Ok, after few hour of research i found the problem:

require order of your components is very important and that was my problem.

On the top of test SignIn component was imported:

import SignIn from '../components/SignIn;

and only after that I mock reportLoginWithEmail in beforeEach that was already initialized in SignIn component, it block checked if mock'ed function was invoked while SignIn component called to non mock'ed function,

so the issue has been resolved by change order of require and remove import of SignIn component on the top of test, working code:

beforeEach(() => {
    biActions = require('../../../actions/BIActions');

    spyOn(biActions, 'reportLoginWithEmail');

    SignIn = require('../../../components/LoginPage/SignIn');
    LoginByEmail = require('../../../components/LoginPage/LoginByEmail');

    component = TestUtils.renderIntoDocument(<SignIn/>);
  });

in that case SignIn component initialized with mock'ed reportLoginWithEmail function