javascript - How to make pass a test case which use enzyme shallow with contains when a React component has an event handler -


i cannot make pass test use .contain when react component has event handler. examples:

foo.js


 const foo = react.createclass({       render () {         return (           <p onclick={() => {}}>i not smart component...</p>         )       }     })  export default foo 

foo.test.js

import react 'react' import { shallow } 'enzyme'  import foo './foo'  describe('<foo />', () => {   it('renders <p> static text', () => {     const wrapper = shallow(<foo />)     console.log(wrapper.debug())     expect(wrapper.contains(<p>i not smart component...</p>)).tobe(true)   }) 

the console result when using .debug() is

<p onclick={[function]}>     not smart component... </p> 

please note onclick={[function]}

i tried change test case to:

describe('<foo />', () => {   it('renders <p> static text', () => {     const wrapper = shallow(<foo />)     console.log(wrapper.debug())     expect(wrapper.contains(<p onclick={() => {}}>i not smart component...</p>)).tobe(true)   }) }) 

but test still not pass.

i know:

  • how fix , make test pass using shallow , .contain , brief explanation why current approach not work.

component instances checked props , values. instance without click handler differs having one.

.contains(nodeornodes) => boolean

returns whether or not given react elements match elements in render tree. determine if element in wrapper matches expected element by checking if expected element has same props wrapper's element , share same values.

also instances having different handlers different.

we can pass click handler prop foo component.

import react 'react'   class foo extends react.component {   render() {     return (       <p onclick={this.props.onclick}>i not smart component...</p>     )   } }  export default foo 

by passing handler props, can inject mock function.

this way can sure prop value passed down click handler mock function.

describe('<foo />', () => {    it('renders <p> static text', () => {     const fn = () => {};     const wrapper = shallow(<foo onclick={fn} />);      expect(wrapper.contains(         <p onclick={fn}>i not smart component...</p>     )).to.be(true);    });  }); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -