简体   繁体   中英

Unit testing select element's `onChange` function with Enzyme

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!

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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM