Enzyme onclick spy toHaveBeenCalled 测试在测试箭头功能时不起作用

IT技术 reactjs enzyme
2021-05-23 01:47:24

我如何测试子组件 onclick。

请看下面的片段。

// App.js

import React, {Component, Fragment} from 'react'
import Child from './child'

class App extends Component{

  state = {
    data: null,
    enable: false
  }

  componentDidMount(){
    this.getData()
  }

  getData = async () => {
    const response = await fetch('http://www.example.com');
    const data = await response.json();
    this.setState({
      data
    })
  }

  _handleChildClick = () => {
    this.setState({
      enable: true
    })
  }

  render(){
    const {data, enable} = this.state
    if(!data){
      return (
       <div>
         Loading
       </div>
      )
    }else{
      <Fragment>
        <Child
         handleChildClick={this._handleChildClick}
        />
      </Fragment>
    }
  }
}


export default App


import React from 'react';

const child = () => {
  return(
    <div>
      <button
        className="toggle"
        onClick={props.handleChildClick}
      >
      Toggle
      </button>
    </div>
  )
}

export default child

// App.test.js

import React from 'react';
import {enzyme} from 'enzyme';
import App from './App';

describe("App test cases", () => {
  it('should trigger _handleChildClick', async () => {
    window.fetch = jest.fn().mockImplementation(() => ({
      status: 200,
      json: () => new Promise((resolve, reject) => {
        resolve(
            {
              name: "some data"
            }
        )
      })
    })) 
    const mountWrapper = await mount(<App />)
    setTimeout(() => {
       mountWrapper.update()
             const SpyhandleChildClick = jest.spyOn(mountWrapper.instance(),'_handleChildClick')
      mountWrapper.find('.toggle').simulate('click')
      expect(SpyhandleChildClick).toHaveBeenCalled() // not called 
    },0)
  })
})
1个回答

需要考虑的一些要点。

测试中的异步代码

如果您必须在测试中执行异步任务,则始终必须等待异步任务完成。

setTimeout(() => {
   mountWrapper.update()
         const SpyhandleChildClick = jest.spyOn(mountWrapper.instance(),'_handleChildClick')
  mountWrapper.find('.toggle').simulate('click')
  expect(SpyhandleChildClick).toHaveBeenCalled() // not called 
},0)

在您的代码上方,您有一个超时段。不会评估此代码块内的任何测试条件,因为在评估它们时,由于 aync 性质,您的“测试会话”已经结束。

在 React 中使用酶测试箭头函数 - forceUpdate()

酶库似乎存在问题,您必须在监视后强制更新react组件才能锁定方法。请关注 github 问题以获取更多信息:https : //github.com/airbnb/enzyme/issues/365

我还清理了您的测试代码,使其更易于理解!

// App.test.js

import React from 'react';
import {enzyme} from 'enzyme';
import App from './App';


describe("App test cases", () => {
  it("should trigger _handleChildClick", async () => {
    window.fetch = jest.fn().mockImplementation(() => ({
      status: 200,
      json: () =>
        new Promise((resolve, reject) => {
          resolve({
            name: "some data"
          });
        })
    }));

    const mountWrapper = mount(<App />);
    mountWrapper.update();
    console.log("mountWrapper", mountWrapper.debug()); // showing the loader one

    //[FIX]This code will block and wait for your asynchronous tasks to be completed
    await new Promise(res => setTimeout(() => res(), 0));

    mountWrapper.update();
    console.log("mountWrapper", mountWrapper.debug()); // nothing showing
    expect(mountWrapper.find(".toggle").length).toEqual(1);

    //[FIX]Get a reference from the wrapper and force update after the spyOn call
    const instance = mountWrapper.instance();
    const spy = jest.spyOn(instance, "_handleChildClick");
    instance.forceUpdate();

    mountWrapper.find(".toggle").simulate("click");

    expect(spy).toHaveBeenCalled();
  });
});

现场演示链接:点击浏览器的“Tests”标签查看测试结果 https://codesandbox.io/s/mz21kpm37j