Categories
Uncategorized

Unit testing method called with parameters

The following two unit tests demonstrate the scenario where you would want to write a unit test to verify whether a method was called with the required parameters. It also tests how many times a method was invoked by passing a mock method.

Enzyme

import { shallow } from 'enzyme';
import sinon from 'sinon';

import Foo from './Foo';

describe('Random Component', () => {
  it('should render blah blah...', () => {
    const onButtonClick = sinon.spy();
    const wrapper = shallow(<Foo funcToBeCalled={onButtonClick} />);
    wrapper.find('button').simulate('click');
    expect(onButtonClick.calledOnce).to.equal(true);
    expect(onButtonClick.calledWith('param1', 'param2')).to.equal(true);
  });

  ...
});

Jest

import { shallow } from 'enzyme';
...

import Foo from './Foo';

describe('Random Component', () => {
  it('should render blah blah...', () => {
       const mockFunction = jest.fn();
       const wrapper = shallow(<Foo funcToBeTested={mockFunction} />);
       wrapper.find('button').simulate('click');
       expect(mockFunction.mock.calls.length).toBe(<span class="hljs-number">1</span>);
       expect(mockFunction).toBeCalledWith('param1', 'param2');
   });

   ...
});