模拟函数在标签内单击按钮后未被标识为调用<a>



>我有一个局部函数,应该在单击按钮时调用该函数,并在其中设置布尔变量的状态。我尝试向此模块添加单元测试,以确定是否单击了按钮并在单击按钮后调用了该函数。

但我的测试失败了。我尝试在"描述"方法中模拟函数,但它不起作用。

某个组件.js

class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        openImagesDialog: false,
    }
  }
  fuctionToBeCalled = (val) => {
      this.setState({ openImagesDialog: val })
  }
  render() {
    return (
      <a onClick={() => this.fuctionToBeCalled(true)} className="img-container float">
        {child components....}
      </a>
    )
  }
}

SomeComponent.test.js

import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import SomeComponent from '../SomeComponent';
import SomeAnotherComp from "../SomeAnotherComp";
Enzyme.configure({ adapter: new Adapter() })
function setup() {
  const props = {
    openImagesDialog: false
  }
  let enzymeWrapper = shallow(<SomeComponent {...props} />)
  return {
    props,
    enzymeWrapper
  }
}
describe('components', () => {
  const { props, enzymeWrapper } = setup()
  it('should call fuctionToBeCalled(){}', () => {
    const SomeAnotherCompProps = enzymeWrapper.find(SomeAnotherComp).props()
    const fuctionToBeCalled = jest.fn(()=>true);

    enzymeWrapper.find('a').simulate('click')
    expect(fuctionToBeCalled).toBeCalled();
    //expect(SomeAnotherCompProps.dialogOpen).toBe(true)
  })
})

我想知道有没有其他方法可以尝试一下。

首先,openImagesDialog不是道具,而是组件中的状态。其次,fuctionToBeCalled是在组件实例上定义的函数,您需要对其进行spy,而不仅仅是创建一个模拟函数。为此,您可以在组件实例上使用spyOn。您还可以在模拟点击后检查状态

import React from 'react'
import Enzyme, { shallow, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import SomeComponent from '../SomeComponent'
import SomeAnotherComp from "../SomeAnotherComp";
Enzyme.configure({ adapter: new Adapter() })
function setup() {
  const props = {
    openImagesDialog: false
  }
  let enzymeWrapper = shallow(<SomeComponent {...props} />)
  return {
    props,
    enzymeWrapper,
  }
}
describe('components', () => {
  const { props, enzymeWrapper } = setup()
  it('should call fuctionToBeCalled(){}', () => {
    const SomeAnotherCompProps = enzymeWrapper.find(SomeAnotherComp).props()
    const instance = enzymeWrapper.instance();
    jest.spyOn(instance, 'fuctionToBeCalled');
    enzymeWrapper.find('a').simulate('click')
    expect(instance.fuctionToBeCalled).toBeCalled();
    expect(enzymeWrapper.state('openImagesDialog')).toEqual(true);
  })
})

最新更新