2

I have a dropdown component in React that renders a select element with some options. Here is what my test looks like:

import React from 'react';
import { shallow, mount } from 'enzyme';
import expect from 'expect';
import Dropdown from './Dropdown';

fdescribe('Dropdown', () => {
  it('should trigger onChange', () => {
    const handleChange = jasmine.createSpy('handleChange');
    const dropdown = mount(
      <div>
        <Dropdown
          options={[
            { key: '', display: 'Please select a value' },
            { key: 'NJ', display: 'New Jersey' },
            { key: 'NY', display: 'New York' },
          ]}
          onChange={handleChange}
        />
      </div>,
     );
    dropdown.find('select').simulate('change', { target: { value: 'New Jersey' } });
    expect(handleChange).toHaveBeenCalled();
  });
});

I get the following error in the console: The "actual" argument in expect(actual).toHaveBeenCalled() must be a spy

Any ideas on how to test the onchange() on the dropdown? Thanks!

Ralph David Abernathy
  • 5,230
  • 11
  • 51
  • 78
  • 1
    `When there is not a function to spy on, jasmine.createSpy can create a "bare" spy. [...] But there is no implementation behind it.` That actually means that this is an artificial spy you have to call yourself. `onChange={handleChange}` maybe wrong try `onChange={() => handleChange()}`. Just guessing here but you want handleChange to be a function so call it like a function. – getjackx Jul 20 '17 at 14:26

1 Answers1

1

The syntax below was what helped me test the value of a select element.

it('should trigger onChange', () => {
  const dropdown = mount(<App />);
  dropdown.find("select").simulate("change",{target: { value : "New Jersey"}});
  expect(dropdown.find("select").props().value).toBe("New Jersey");
});
ForTheWin
  • 617
  • 1
  • 8
  • 15