在<a> tag

时间:2019-04-17 05:54:42

标签: reactjs jestjs enzyme

I have a local function that should be called on a button click and set the state of a Boolean variable inside it. I tried to add unit test to this module to identify whether the button is clicked and the function is called following the button click.

But my test is failing. I tried by mock the function inside the 'describe' method yet it didn't work.

SomeComponent.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)
  })
})

I'd like to know is there any other way to try this out.

1 个答案:

答案 0 :(得分:2)

首先,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);
  })
})