Jest spyOn function called

前端 未结 3 1365
栀梦
栀梦 2020-12-02 09:42

I\'m trying to write a simple test for a simple React component, and I want to use Jest to confirm that a function has been called when I simulate a click with enzyme. Accor

3条回答
  •  青春惊慌失措
    2020-12-02 10:12

    In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:

    1) Where the click handler calls a function passed as a prop, e.g.

    class App extends Component {
    
      myClickFunc = () => {
          console.log('clickity clickcty');
          this.props.someCallback();
      }
      render() {
        return (
          
    logo

    Welcome to React

    To get started, edit src/App.js and save to reload.

    ); } }

    You can now pass in a spy function as a prop to the component, and assert that it is called:

    describe('my sweet test', () => {
     it('clicks it', () => {
        const spy = jest.fn();
        const app = shallow()
        const p = app.find('.App-intro')
        p.simulate('click')
        expect(spy).toHaveBeenCalled()
     })
    })
    

    2) Where the click handler sets some state on the component, e.g.

    class App extends Component {
      state = {
          aProperty: 'first'
      }
    
      myClickFunc = () => {
          console.log('clickity clickcty');
          this.setState({
              aProperty: 'second'
          });
      }
      render() {
        return (
          
    logo

    Welcome to React

    To get started, edit src/App.js and save to reload.

    ); } }

    You can now make assertions about the state of the component, i.e.

    describe('my sweet test', () => {
     it('clicks it', () => {
        const app = shallow()
        const p = app.find('.App-intro')
        p.simulate('click')
        expect(app.state('aProperty')).toEqual('second');
     })
    })
    

提交回复
热议问题