Testing onChange function in Jest

前端 未结 5 2038
悲哀的现实
悲哀的现实 2021-02-01 04:07

I\'m relatively new to Jest and testing in general. I have a component with an input element:

import * as React from \"react\";

export interface inputProps{
            


        
5条回答
  •  盖世英雄少女心
    2021-02-01 04:12

    How about this one? I simulate the change event using enzyme and perform a snapshot test. Component

    import React, { FunctionComponent, useState } from 'react';
    
    const Index: FunctionComponent = () => {
    
      const [val, setVal] = useState('');
    
      const onInputChange = e => {
        e.preventDefault();
        setVal(e.target.value);
      };
    
      return (
        
      );
    };
    
    export default Index;
    

    Unit Test

    describe('Index with enzyme', () => {
      it('Should set value to state when input is changed', () => {
        const container = shallow();
        const input = container.find('input');
        input.simulate('change', { preventDefault: jest.fn, target: { value: "foo" } });
        expect(container).toMatchSnapshot();
      });
    });
    

    Snapshot

    exports[`Index with enzyme Should set value to state when input is changed 1`] = `
      
    `;
    

提交回复
热议问题