GithubHelp home page GithubHelp logo

producthunt / chai-enzyme Goto Github PK

View Code? Open in Web Editor NEW
787.0 52.0 73.0 138 KB

Chai.js assertions and convenience functions for testing React Components with enzyme

License: MIT License

JavaScript 100.00%

chai-enzyme's Introduction

chai-enzyme

npm version License Build Status

Chai.js assertions for enzyme.

Table of Contents

  1. Installation
  2. Setup
  3. Debug output in assertion exceptions
  4. Assertions 1. checked() 1. className(str) 1. contain(nodeOrNodes) 1. containMatchingElement(node) 1. descendants(selector)
    1. exactly() 1. disabled() 1. blank() 1. present() 1. html(str) 1. id(str) 1. match(selector) 1. ref(key) 1. selected() 1. tagName(str) 1. text(str) 1. type(func) 1. value(str) 1. attr(key, [val]) 1. data(key, [val]) 1. style(key, [val]) 1. state(key, [val]) 1. prop(key, [val]) 1. props(key, [val])
  5. Development
  6. Contributing
  7. License

Installation

chai-enzyme depends on:

"peerDependencies": {
  "chai": "^3.0.0 || ^4.0.0",
  "cheerio": "0.19.x || 0.20.x || 0.22.x || ^1.0.0-0",
  "enzyme": "^2.7.0 || ^3.0.0",
  "react": "^0.14.0 || ^15.0.0-0 || ^16.0.0-0",
  "react-dom": "^0.14.0 || ^15.0.0-0 || ^16.0.0-0"
}

cheerio is already a dependency of enzyme, so most probably you will not have to install it manually

$ npm install chai-enzyme --save-dev

Setup

import chai from 'chai'
import chaiEnzyme from 'chai-enzyme'

chai.use(chaiEnzyme()) // Note the invocation at the end

Debug output in assertion exceptions

You can also provide a custom debug function that can print useful information about the wrapper that you are using.

The default one that chai-enzyme comes with, will pretty print the HTML of the wrapper under test.

  1) #text (text) (shallow): passes when the actual matches the expected:
     AssertionError: expected <Fixture /> to have text 'Test test', but it has 'Test'

     ---------- this is where the debug output starts ----------

     HTML:

     <span id="child">Test</span>

     ---------- this is where the debug output ends ----------

Here is how you can implement and configure one for yourself:

function myAwesomeDebug (wrapper) {
  let html = wrapper.html()
  // do something cool with the html
  return html
}

chai.use(chaiEnzyme(myAwesomeDebug))

Assertions

It's important to know that all assertions are registered with Chai's overwrite* methods and therefore this plugin can work next to other Chai.js plugins that have similar assertions, such as chai-jquery.

At the beginning of each assertion, we verify if the provided object is a ShallowWrapper, ReactWrapper or a cheerio object and if not we delegate to the next assertion that responds to the given method.

Note that not all assertions work with every rendering strategy.

If you are wondering what rendering mechanism to use when, refer to enzyme's documentation.

checked()

render mount shallow
yes yes yes

Assert that the given wrapper is checked:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <input id='checked' defaultChecked />
        <input id='not' defaultChecked={false} />
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('#checked')).to.be.checked()
expect(wrapper.find('#not')).to.not.be.checked()

className(str)

render mount shallow
yes yes yes

Assert that the wrapper has a given class:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div className='root top'>
        <span className='child bottom'>test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('span')).to.have.className('child')
expect(wrapper.find('span')).to.not.have.className('root')

contain(nodeOrNodes)

render mount shallow
no yes yes

Assert that the wrapper contains a given node or array of nodes:

import React from 'react'
import {mount, render, shallow} from 'enzyme'
import PropTypes from 'prop-types';

class User extends React.Component {
  render () {
    return (
      <span>User {this.props.index}</span>
    )
  }
}

User.propTypes = {
  index: PropTypes.number.isRequired
}

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <ul>
          <li><User index={1} /></li>
          <li>
            <User index={2} />
            <User index={3} />
          </li>
        </ul>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.contain(<User index={1} />)
expect(wrapper).to.contain([<User index={2} />, <User index={3} />])
expect(wrapper).to.not.contain(<User index={3} />)

containMatchingElement(node)

render mount shallow
no yes yes

Assert that the wrapper contains a matching given node:

import React from 'react'
import {mount, render, shallow} from 'enzyme'
import PropTypes from 'prop-types';

class User extends React.Component {
  render () {
    return (
      <span>User {this.props.index} {this.props.name}</span>
    )
  }
}

User.propTypes = {
  index: PropTypes.number,
  name: PropTypes.string.isRequired
}

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <ul>
          <li><User index={1} name='John' /></li>
          <li><User index={2} name='Doe' /></li>
        </ul>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.containMatchingElement(<User name='John' />)
expect(wrapper).to.not.containMatchingElement(<User name='Conor' />)

descendants(selector)

render mount shallow
yes yes yes

Assert that the wrapper contains a descendant matching the given selector:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class User extends React.Component {
  render () {
    return (
      <span>User</span>
    )
  }
}

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <User />
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.descendants('#root')
expect(wrapper).to.have.descendants(User)

expect(wrapper).to.not.have.descendants('#root1')

exactly()

render mount shallow
yes yes yes

Assert that the wrapper contains an exact amount of descendants matching the given selector:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <span id='child'>
          <span class='item'></span>
          <span class='item'></span>
        </span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.exactly(2).descendants('.item')

disabled()

render mount shallow
yes yes yes

Assert that the given wrapper is disabled:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <input id='disabled' disabled />
        <input id='not' />
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('#disabled')).to.be.disabled()
expect(wrapper.find('#not')).to.not.be.disabled()

blank()

render mount shallow
yes yes yes

Assert that the given wrapper is empty:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='parent'>
        <div id='child'>
        </div>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('#child')).to.be.blank()
expect(wrapper.find('#parent')).to.not.be.blank()

expect(wrapper.find('#child')).to.be.empty // an alias
expect(wrapper.find('#parent')).to.not.be.empty // an alias

class NullFixture extends React.Component {
  render () {
    return null
  }
}

const nullWrapper = mount(<NullFixture />) // mount/render/shallow when applicable

expect(nullWrapper).to.be.blank()
expect(nullWrapper).to.be.empty // an alias

present()

render mount shallow
yes yes yes

Assert that the given wrapper exists:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='parent'></div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('#parent')).to.be.present()
expect(wrapper.find('#parent')).to.exist // an alias

class NullFixture extends React.Component {
  render () {
    return null
  }
}

const nullWrapper = mount(<NullFixture />) // mount/render/shallow when applicable

expect(nullWrapper).to.be.present()
expect(nullWrapper).to.exist // an alias

html(str)

render mount shallow
yes yes yes

Assert that the wrapper has given html:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <span id='child'>Test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('#child')).to.have.html('<span id="child">Test</span>')

expect(wrapper.find('#child')).to.not.have.html('<span id="child">Test 1</span>')

expect(wrapper.find('#child')).to.have.html().match(/Test/)

id(str)

render mount shallow
yes yes yes

Assert that the wrapper has given ID attribute:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <span id='child'>test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.id('root')
expect(wrapper).to.not.have.id('child')

match(selector)

render mount shallow
yes yes yes

Assert that the wrapper matches given selector:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <span id='child'>test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('span')).to.match('#child')
expect(wrapper.find('#root')).to.not.match('#child')

ref(key)

render mount shallow
no yes no
import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <input ref='test' />
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.ref('test')
expect(wrapper).to.have.ref('random')

selected()

render mount shallow
yes yes no

Assert that the given wrapper is selected:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <select defaultValue='test1'>
        <option id='test1' value='test1'>Test 1</option>
        <option id='test2' value='test2'>Test 1</option>
      </select>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('#test1')).to.be.selected()
expect(wrapper.find('#test2')).to.not.be.selected()

tagName(str)

render mount shallow
yes yes yes

Assert that the given wrapper has the tag name:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <span />
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.tagName('div')
expect(wrapper.find('span')).to.have.tagName('span')

expect(wrapper).to.not.have.tagName('a')
expect(wrapper.find('span')).to.not.have.tagName('a')

text(str)

render mount shallow
yes yes yes

Assert that the given wrapper has the supplied text:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <span id='child'>Test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('#child')).to.have.text('Test')

expect(wrapper.find('#child')).to.contain.text('Te')
expect(wrapper.find('#child')).to.include.text('Te') // include is an alias of contain

expect(wrapper.find('#child')).to.not.have.text('Other text')
expect(wrapper.find('#child')).to.not.include.text('Other text') // include is an alias of contain

expect(wrapper.find('#child')).to.have.text().match(/Test/)

type(func)

render mount shallow
no yes yes

Assert that the given wrapper has a given type:

import React from 'react'
import {shallow} from 'enzyme'

class Foo extends React.Component {
  render () {
    return (
      <div>Foo</div>
    )
  }
}

class Bar extends React.Component {
  render () {
    return (
      <div>Bar</div>
    )
  }
}

class Fixture extends React.Component {
  render () {
    return (
      <Foo />
    )
  }
}

const shallowWrapper = shallow(<Fixture />)
const mountWrapper = mount(<Fixture />)

expect(shallowWrapper).to.have.type(Foo)
expect(shallowWrapper).to.not.have.type(Bar)

expect(mountWrapper).to.have.type(Fixture)
expect(mountWrapper).to.not.have.type(Bar)

value(str)

render mount shallow
yes yes yes

Assert that the given wrapper has given value:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <input defaultValue='test' />
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('input')).to.have.value('test')
expect(wrapper.find('input')).to.not.have.value('other')

attr(key, [val])

render mount shallow
yes yes yes

Assert that the wrapper has given attribute [with value]:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <span id='child'>test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find('span')).to.have.attr('id')
expect(wrapper).to.not.have.attr('disabled')

expect(wrapper).to.have.attr('id', 'root')
expect(wrapper).to.not.have.attr('id', 'invalid')

expect(wrapper).to.have.attr('id').equal('root')

data(key, [val])

render mount shallow
yes yes yes

Assert that the wrapper has a given data attribute [with value]:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div data-name='root'>
        <span data-name='child'>test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.data('name')
expect(wrapper).to.not.have.data('random')

expect(wrapper).to.have.data('name', 'root')
expect(wrapper).to.not.have.data('name', 'invalid')

expect(wrapper).to.have.data('name').equal('root')

style(key, [val])

render mount shallow
yes yes yes

Assert that the wrapper has given style:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  render () {
    return (
      <div style={{ border: 1 }}>
        <span style={{ color: 'red' }}>test</span>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.style('border')
expect(wrapper).to.not.have.style('color')
expect(wrapper).to.have.style('margin-top') // do not use camelCase keys as you would do in your React component

expect(wrapper).to.have.style('border', '1px')
expect(wrapper).to.not.have.style('border', '2px')

expect(wrapper).to.have.style('border').equal('1px')

state(key, [val])

render mount shallow
no yes yes

Assert that the wrapper has given state [with value]:

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class Fixture extends React.Component {
  constructor () {
    super()
    this.state = { foo: 'bar' }
  }

  render () {
    return (
      <div id='root'>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.state('foo')
expect(wrapper).to.not.have.state('bar')


expect(wrapper).to.have.state('foo', 'bar')
expect(wrapper).to.not.have.state('foo', 'baz')

expect(wrapper).to.have.state('foo').equal('bar')

prop(key, [val])

render mount shallow
no yes yes

Assert that the wrapper has given prop [with value]:

import React from 'react'
import {mount, render, shallow} from 'enzyme'
import PropTypes from 'prop-types';

class User extends React.Component {
  render () {
    return (
      <span>User {this.props.index}</span>
    )
  }
}

User.propTypes = {
  index: PropTypes.number.isRequired
}

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <ul>
          <li><User index={1} user={{name: 'Jane'}} /></li>
          <li><User index={2} /></li>
        </ul>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find(User).first()).to.have.prop('index')
expect(wrapper.find(User).first()).to.not.have.prop('invalid')


expect(wrapper.find(User).first()).to.have.prop('index', 1)
expect(wrapper.find(User).first()).to.not.have.prop('index', 2)

expect(wrapper.find(User).first()).to.have.prop('index').equal(1)
expect(wrapper.find(User).first()).to.have.prop('user').deep.equal({name: 'Jane'})

props(key, [val])

render mount shallow
no yes yes

Assert that the wrapper has given set of props [with values]:

import React from 'react'
import {mount, render, shallow} from 'enzyme'
import PropTypes from 'prop-types';

class User extends React.Component {
  render () {
    return (
      <span>User {this.props.index}</span>
    )
  }
}

User.propTypes = {
  index: PropTypes.number.isRequired
}

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <ul>
          <li><User index={1} user={{name: 'Jane'}} /></li>
          <li><User index={2} /></li>
        </ul>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper.find(User).first()).to.have.props([ 'index', 'user' ])
expect(wrapper.find(User).first()).to.not.have.props([ 'invalid' ])


expect(wrapper.find(User).first()).to.have.props({ index: 1 })
expect(wrapper.find(User).first()).to.not.have.props({ index: 2 })

expect(wrapper.find(User).first()).to.have.props([ 'index', 'user' ]).deep.equal([ 1, { name: 'Jane' } ])

Development

Setup

$ git clone <this repo>
$ cd chai-enzyme
$ npm install

Tests

Linters:

$ npm run test:lint

Tests:

$ npm run test:unit

All:

$ npm test

Contributing

We want to make this assertion library as robust and complete as possible. If you think that there are missing features/assertions, please open a GitHub issue or even better - a PR.

Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

Product Hunt

 _________________
< The MIT License >
 -----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

chai-enzyme's People

Contributors

armsteadj1 avatar ayrton avatar brucewpaul avatar chibicode avatar dylanscott avatar eavae avatar gcedo avatar greenkeeperio-bot avatar gustavohenke avatar jeffcarbs avatar julioolvr avatar keithamus avatar lencioni avatar marcodejongh avatar n3dst4 avatar okize avatar remcohaszing avatar rik avatar rylanc avatar smacker avatar spencercdixon avatar superzadeh avatar tagoro9 avatar vesln avatar wbyoung avatar zahermustapha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chai-enzyme's Issues

Getting "Cannot read property 'hasDescendants' of undefined"

at Assertion.descendants (/Users/matthew.spence/Projects/tripapplite/node_modules/chai-enzyme/build/assertions/descendants.js:13:22)
      at Assertion.<anonymous> (/Users/matthew.spence/Projects/tripapplite/node_modules/chai-enzyme/build/index.js:139:19)
      at Assertion.ctx.(anonymous function) [as descendants] (/Users/matthew.spence/Projects/tripapplite/node_modules/chai/lib/chai/utils/addMethod.js:41:25)
      at Context.<anonymous> (/Users/matthew.spence/Projects/tripapplite/app/assets/javascripts/tripapp_specs_mocha.js:218703:53)
      at callFn (/Users/matthew.spence/Projects/tripapplite/node_modules/mocha/lib/runnable.js:250:21)
      at Test.Runnable.run (/Users/matthew.spence/Projects/tripapplite/node_modules/mocha/lib/runnable.js:243:7)
      at Runner.runTest (/Users/matthew.spence/Projects/tripapplite/node_modules/mocha/lib/runner.js:373:10)
      at /Users/matthew.spence/Projects/tripapplite/node_modules/mocha/lib/runner.js:451:12
      at next (/Users/matthew.spence/Projects/tripapplite/node_modules/mocha/lib/runner.js:298:14)
      at /Users/matthew.spence/Projects/tripapplite/node_modules/mocha/lib/runner.js:308:7

`blank()` does not return errors for non-null components as suggested

I was struggling to get blank() to fail when a component had content. I eventually copied the exact code from the example but had it return content rather than null:

class NullFixture extends React.Component {
  render () {
    return (<p>hi</p>)
  }
}

The example tests do not fail (they pass):

const nullWrapper = mount(<NullFixture />) // mount/render/shallow when applicable

expect(nullWrapper).to.be.blank()
expect(nullWrapper).to.be.empty

react-element-to-jsx-string requires react 15 :-(

I'm using React 0.14, and react-element-to-jsx-string has a direct dependency (not a peer dep) on react-addons-test-utils - https://npmcdn.com/[email protected]/package.json.

This means that a normal npm install will install a 15.x version of react-addons-test-utils, which will then complain that my React 0.14 doesn't work.

react-element-to-jsx-string needs to have a peer dep on react-addons-test-utils, not a direct dep.

I'm filing this here, since this is manifesting as a bug in chai-enzyme in that npm ls doesn't work when i install it.

Type assertion

Currently there is no way of asserting that a certain wrapper is a of a certain type.
So when asserting on type I have to resort to doing this:

expect(wrapper.type()).to.equal(SomeComponent);

Ideally I would think the assertion should look like this:

expect(wrapper).to.be.of.type(SomeComponent);

OR

expect(wrapper).to.have.type(SomeComponent);

Any thoughts? I will try to implement this tomorrow, taking any opinions voiced in this issue into consideration.

Support for counting all child elements

Occasionally I have situations where I want to do assertions on markup that might have child nodes inserted into it. I want to do tests where there are known children and to make sure that they are inserted correctly.

The problem here is that the children could be any nodes at all, and I want to make sure that no unexpected nodes are appearing in the element tree. It seems the easiest way of doing this is to be able to assert on the number of elements without needing a specific selector to find them. E.g.

const TestComponent = ({children}) => (
    <div className="a">
        <div className="b"></div>
        <span className="c"></span>
        {children}
        <div className="d"></div>
        <span className="e"></span>
    </div>
);

expect(shallow(<TestComponent></TestComponent>).find(".a")).to.have.exactly(4).children());
expect(shallow(<TestComponent><a></a></TestComponent>).find(".a")).to.have.exactly(5).children());

to.have assertions fail with 'TypeError: Cannot read property '<prop_name>' of undefined'

I'm trying to use to.have.text assertion for my component test but it fails for me with TypeError: Cannot read property 'text' of undefined
To demonstrate, I've tried an example from your docs:

import * as React from 'react';
import * as chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { shallow } from 'enzyme';

chai.use(chaiEnzyme());

class Fixture extends React.Component<{}, {}> {
  render () {
    return (
      <div id='root'>
        <span id='child'>Test</span>
      </div>
    );
  }
}

const wrapper = shallow(<Fixture />);
chai.expect(wrapper.find('#child')).to.have.text('Test');

Here's the full stacktrace:

var actual = wrapper.text();
                      ^

TypeError: Cannot read property 'text' of undefined
    at Assertion.text (/Users/liss/Work/Dev/Git/denali/node_modules/chai-enzyme/build/assertions/text.js:15:23)
    at Assertion.<anonymous> (/Users/liss/Work/Dev/Git/denali/node_modules/chai-enzyme/build/ChaiWrapper.js:193:19)
    at Assertion.ctx.(anonymous function) [as text] (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:47531:26)
    at Object.<anonymous> (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:43219:46)
    at __webpack_require__ (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:21:30)
    at Object.module.exports._typeof (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:43248:2)
    at __webpack_require__ (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:21:30)
    at Object.<anonymous> (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:74:19)
    at __webpack_require__ (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:21:30)
    at /Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:41:18
    at Object.<anonymous> (/Users/liss/Work/Dev/Git/denali/dist_test/client/main.js:44:10)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at /Users/liss/Work/Dev/Git/denali/node_modules/mocha/lib/mocha.js:220:27
    at Array.forEach (native)
    at Mocha.loadFiles (/Users/liss/Work/Dev/Git/denali/node_modules/mocha/lib/mocha.js:217:14)
    at Mocha.run (/Users/liss/Work/Dev/Git/denali/node_modules/mocha/lib/mocha.js:469:10)
    at Object.<anonymous> (/Users/liss/Work/Dev/Git/denali/node_modules/mocha/bin/_mocha:404:18)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

It looks like applicable to all to.have assertions
chai-enzyme version is 0.5.0

TypeError: Cannot read property 'call' of undefined

I know im not giving a ton of information here, but im really not sure what is causing this issue.

I'm using webpack to compile everything

        TypeError: Cannot read property 'call' of undefined
            at ReactWrapper.single (webpack:///~/enzyme/build/ReactWrapper.js:1329:0 <- tests.webpack.js:51035:19)
            at ReactTestWrapper.get (webpack:///~/chai-enzyme/build/ReactTestWrapper.js:128:0 <- tests.webpack.js:90179:35)
            at ReactTestWrapper.style (webpack:///~/chai-enzyme/build/ReactTestWrapper.js:61:0 <- tests.webpack.js:90112:19)
            at Assertion.<anonymous> (webpack:///~/chai-enzyme/build/assertions/generic.js:17:0 <- tests.webpack.js:49143:37)
            at Assertion.<anonymous> (webpack:///~/chai-enzyme/build/ChaiWrapper.js:193:0 <- tests.webpack.js:49589:20)
            at Assertion.ctx.(anonymous function) [as style] (webpack:///~/chai/lib/chai/utils/addMethod.js:41:0 <- tests.webpack.js:8460:26)
            at Context.<anonymous> (webpack:///tests/components/Image.test.js:75:57 <- tests.webpack.js:160:59)

and the code:

const images = [
            '/23649/movie/3/1132905.jpg',
            '/23649/movie/3/1132906.jpg',
            '/23649/movie/3/1132907.jpg'
        ];

        const component = mount(<Image
            image={{url: images[0]}}
            preload={[
                {url: images[1]},
                {url: images[2]}
            ]}
        />);

        expect(component).to.be.present();
        expect(component.find('.current-image')).to.be.present();
        expect(component.find('.current-image')).to.have.style('backgroundImage');

The last line there, is line 75 of Image.test.js

Shallow `contain` fails

The documentation for contain states that I can assert a shallow wrapper contains a node, but this SSCE fails:

import React, {Component} from 'react';

function ChildComponent() {
  return <div className="child" />;
}

class MyComponent extends Component {
  render() {
    return (
      <div>
        <ChildComponent />
      </div>
    );
  }
}

describe('My Component', function () {
  it('renders the child', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper).to.contain(<ChildComponent />);
  });

  it('finds the child', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(ChildComponent)).to.have.length(1);
  });
});

it('renders the child') throws the following error:

AssertionError: expected { Object (root, unrendered, ...) } to have a property '$$typeof'

but it('finds the child') passes.

(Note that I have expect and shallow available as globals in my Mocha test env.)

Are the docs wrong or am I using this method incorrectly?

Cannot read property 'replace' of undefined

I'm currently getting the following error when using mount() - Uncaught TypeError: Cannot read property 'replace' of undefined with the latest version of chai-enzyme.
If I revert to the previous [email protected] there is no error and all runs ok. I haven't been able to track the cause yet.

Dependency versions:

[email protected]
[email protected]
[email protected]
[email protected]

Basic example of test that causes the in browser error:

import 'babel-polyfill';
import ArticleTemplate from '../src';
import React from 'react';
import article from '../stubbed/article';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { mount } from 'enzyme';

chai.use(chaiEnzyme()).should();

describe('ArticleTemplate', () => {
  let props = null;
  beforeEach(() => {
    props = {
      id: article.id,
      slug: article.slug,
      content: article.content,
    };
  });

  it('renders a React element', () => {
    React.isValidElement(<ArticleTemplate {...props} />).should.equal(true);
  });

  describe('Rendering', () => {
    let rendered = null;
    let articlePage = null;
    beforeEach(() => {
      rendered = mount(<ArticleTemplate {...props} />);
      articlePage = rendered.find('.article-template');
    });

    it('renders <article />', () => {
      articlePage.should.have.tagName('article');
    });
  });
});

TDD assertion style

Chai supports TDD-style assertions in the form of assert.equal(), assert.include(), etc. Is it possible for that to be added to chai-enzyme? From briefly looking at the code, I think it could easily be done either by modifying ChaiWrapper or by explicitly defining each assertion in terms of an expect/should function. It would probably be helpful to work with chai-tdd-plugins to make sure function name collisions are avoided.

Components returning null with different results for render and shallow

I came across an interesting inconsistency, let me demonstrate this with some code, here's a simplified version of my ContentToggle component:

export default class ContentToggle extends React.Component {
  props: {
    component: Function|string,
    content: ?ReactElement,
    options: ?Array<ReactElement>,
  };

  render(): ?ReactElement {
    const {content, options, ...otherProps} = this.props;

    if (!content && !options) {
      return null;
    }

    return React.createElement('a', { href: '#', ...otherProps });
  }
}

Important to note is that I either need to pass on content or options as props or otherwise it will return null.

My initial tests I wrote:

describe(ContentToggle.displayName, () => {
  it('renders children if content is passed', () => {
    const children = 'FOO';
    const el = render(<ContentToggle content={<span />}>{children}</ContentToggle>);

    expect(el).to.have.text(children);
  });

  it('renders children if options are passed', () => {
    const children = 'FOO';
    const el = render(<ContentToggle options={[]}>{children}</ContentToggle>);

    expect(el).to.have.text(children);
  });

 it('renders nothing if no content or options are passed', () => {
    const children = 'FOO';
    const el = render(<ContentToggle>{children}</ContentToggle>);

    expect(el).to.not.have.text(children);
    expect(el).to.be.blank();
  });
});

The first two tests passed, but the third one did not:

  1) undefined renders nothing if no content or options are passed:
     AssertionError: expected the node in <??? /> to be empty

     HTML:

     <noscript></noscript>

When I change the 3rd test to use shallow vs render this test passes, or I can write the test as follow:

describe(ContentToggle.displayName, () => {
  it('renders nothing if no content or options are passed', () => {
    const children = 'FOO';
    const el = render(<ContentToggle>{children}</ContentToggle>);

    expect(el).to.not.have.text(children);
    expect(el.find('noscript')).to.be.blank();
  });
});

I would have expected expect(el).to.be.blank(); to work with both render as with shallow (or mount for that matter), or at least consistent behaviour across all 3.

After discussing this in enzymejs/enzyme#139 we've decided to tackle this within chai-enzyme.

Linking master branch for local development

Hi all,

I was interesting in taking a look at this library to see how it works and if I was able to help contribute, so I decided to pull it down and link my codebase to use the local version of chai-enzyme.

> git clone [email protected]:producthunt/chai-enzyme.git
> cd chai-enzyme
> npm link
> cd ../my-codebase
> npm link chai-enzyme

After doing this and running my test suite, every single test that uses chai-enzyme assertions fails.

TypeError: Cannot read property 'tagName' of undefined
TypeError: Cannot read property 'className' of undefined
TypeError: Cannot read property 'prop' of undefined

And so on. It looks like wrapper is undefined in assertions/tagName.js, assertions/className.js, assertions/generic.js, etc. After unlinking and pulling the latest version down from npm, these failures go away.

So I guess my question is, am I doing something wrong here? Why do my tests fail when I link to chai-enzyme from a local folder?

Assertion tagName tries to shallowrender the given component

When using the following assertion:

expect(wrapper.children().at(1)).to.have.tagName('td');

I get a error because on of the props of the child of the wrapper at 1 is undefined.

If I remove the tagName assertion and just leave this one:

 expect(wrapper.children().at(1)).to.have.prop('className', 'action');

The error is gone. So there is a discrepancy between how to.have.prop and to.have.tagName do their assertions.

Contain doesn't work in react 15?

I just upgraded to react 15.0.1, enzyme 2.3.0, and chai-enzyme 0.4.2. I have a pretty simple test:

    const component = enzymeShallow(
      <ParentComponent {...props}/>
    )

    expect(component).to.contain(ChildComponent)

I get this error:

ShallowWrapper::contains() can only be called with ReactElement (or array of them), string or number as argument.

The only odd thing is that ChildComponent is a sinon stub, but the error indicates that it never even got to the actual assertion. What am I doing wrong?

Assertions on result of wrapper.get

Assertions of result of get are currently not possible

expect(wrapper.children().get(1)).to.have.tagName('td');

Should work the same as

expect(wrapper.children().at(1)).to.have.tagName('td');

Why does tagName assertion delegate to the name property on shallow/cheerio wrapper?

I'm a bit confused by the implementations of tagName on some of the wrappers where they delegate to the element's name property: https://github.com/producthunt/chai-enzyme/blob/master/src/ShallowTestWrapper.js#L44.

According to MDN the name property only exists for certain elements. Why do the shallow and cheerio wrappers not use tagName? I have failing assertions assertions like:

class MySpanComponent extends React.Component {
  render() {
    return (<span />);
  }
}

// Fails because .name is undefined; .tagName is the expected "SPAN"
expect(shallow(<MySpanComponent />)).to.have.tagName('span')

Is this an issue with chai-enzyme or am I doing something wrong/missing something? Thanks!

Tests fail with Enzyme 2.5.0

Enzyme 2.5.0 was released 12 hours ago. With that version, .to.have.attr (and probably other) calls are failing with an error of cannot read property "call" of undefined.

Running chia-enzyme tests with [email protected], all 373 tests pass.

Running chai-enzyme tests with [email protected], 312 passing, 61 failing.

New Release?

Just curious when you plan to release the next version of chai-enzyme. Currently, I'm getting a few deprecation warnings stemming from chai-enzyme's dependencies (that I see have been corrected on the master branch).

How to get it working in Karma?

On react-boilerplate/react-boilerplate#79 (comment) (see link for more info) we are trying to convert from mocha/jsdom to Karma/Chrome.

I tried to create a Karma plugin for chai-enzyme (a naive copy paste based on another karma-chai-foobar) but I'm having trouble with the fact that chai-enzyme is published as an ES6 module, and Karma doesn't understand that.

I admit I am pretty fuzzy when it comes to implementation details of require, CommonJS, ES modules, etc. I know even less about Karma plugins.

How could we get this working?

Value assertion does not work on HTML <select> elements

If I have this element:

<input value={1} />

This assertion is true, as expected:

element.should.have.value(1)

If I have this element:

<select value={1}>
    <option value={1}>1</option>
</select>

The same assertion fails, value is supposedly undefined.

Assertion for shallow rendering `equals`

It would be nice to have assertion to check node against node, equals from shallow rendering of enzyme (probably equalsJSX, same to https://github.com/algolia/expect-jsx)

Now

expect(shallow(<Component />).find('SubComponent').equals(<SubComponent foo="bar" />)).to.be.true

Would like to have

expect(shallow(<Component />).find('SubComponent')).to.be.equalsJSX(<SubComponent foo="bar" />)

`attr` fails for falsey attribute values

Hey everyone, great work on the awesome chai plugin!

The .attr() assertion fails when asserting on an attribute with a falsey value, such as an empty string.

Consider the following html:

<article itemscope itemtype="http://schema.org/Article" itemprop="article"></article>

Asserting expect(article).to.have.attr('itemscope') fails when using enzyme's mount. It fails because ReactTestWrapper calls getAttribute(name) || undefined - and the itemscope's result from getAttribute is ''.

It should be noted that (although I haven't actually tested) - I believe that the CheerioWrapper won't do the same (it doesn't use || undefined in the wrapper code and Cheerio itself returns the property verbatum).

Solution

Do not use || undefined. Instead pass the attribute verbatim. getAttribute will return null for attributes which don't exist on the element, which can be used to accurately detect the lack of an attribute over falsey values.

matcher for `is`

I tried expect(foo).to.be.a('bar') to be a nicer form of expect(foo.is('bar')).to.equal(true), but it didn't work. What do you all think about a matcher for this?

some/any, every, none assertions

I'm having trouble with handling cases involving multiple nodes. My team generally doesn't like to change the source code purely for the sake of the tests, so we can't really use find on an id since usually we wouldn't otherwise need an id. Therefore our tests look like this:

  context('with an adminPath passed as a prop', () => {
    it('renders a link to the admin page', () => {
      const adminPath = '/admin';
      const actual = shallow(<MyComponent {...{ adminPath }}).find({ href: adminPath });
      expect(actual).to.be.present();
    });
  });

This works, but a failing test gives us something like "expected false to be true." We could use the enzyme helpers here such as some or someWhere, but those are really matchers, not assertions. We end up having to use .length.to.equal(1) or something similar, which doesn't really convey the true meaning of the test.

I think it would be great if we could have some sort of API like this:

const adminPath = '/admin';
const actual = shallow(<MyComponent {...{ adminPath }});
expect(actual).any.to.haveAttr('href', adminPath);

The inverse would be:

const adminPath = '/admin';
const actual = shallow(<MyComponent {...{ adminPath }});
expect(actual).none.to.haveAttr('href', adminPath);

Is there an alternative that I missed?

If no, is this feasible? I would imagine it would involve somehow extending enzyme, as this is where the non property would have to come from. If this is possible, I'd be happy to help!

State should allow to check against primitives like []

Hi all,

first of all, thank you for this plugin. It makes testing with enzyme a little less painful ๐Ÿ‘.
I just wanted to try the .state check on a fairly simple component that currently looks like this:

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
  }
}

The test looks like this:

describe('MyComponent', function() {

  describe('when initializing the component', function() {
    it('should set a default state', function() {
      const component = shallow(<Component />);
      expect(component).to.have.state('items', []);
    });
  });
});

_Current behaviour:_
AssertionError: expected to have a 'items' state with the value [], but the value was [].

_Expected Behaviour:_
I would expect the output to be true, e.g. a deep check should happen instead of a regular one.

_Additional Input:_
It would be nice if we could also write something like this if the first parameter of state is a plain object to deep check everything:

expect(MyComponent).to.have.state({
  items: []
});

This would be equivalent to the currently used function below:

expect(MyComponent.state()).to.deep.equal({
  items: []
});

Thank you again for writing this beauty, hope the feedback is helpful for you.

Issue using chai-enzyme alongside chai-jquery

The root of the problem appears to stem from the fact that chai-jquery uses checked as a property:

expect($(node)).to.be.checked;

While chai-enzyme implements it as an assertion method:

expect(wrapper).to.be.checked();

If I call chai.use with chai-jquery first, chai-enzyme chokes while trying to add the checked assertion (chaiWrapper.addAssertion(checked, 'checked')):
Uncaught TypeError: Cannot read property 'is' of undefined

If I call chai.use with chai-enzyme first, chai-jquery overwrites the checked assertion as a property.

Any ideas on how to make them play nice together?

.not.to.exist assertion doesn't work with mount()

chai-enzyme version: 0.4.0
enzyme version: 1.5.0

I'm running into an issue where asserting that an empty wrapper is not present() works in components rendered with shallow but not with mount. Minimal repro:

const shallowWrapper = shallow(<div/>)
expect(shallowWrapper.find('#notfound')).not.to.exist // โœ“
const mountWrapper = mount(<div/>)
expect(mountWrapper.find('#notfound')).not.to.exist // โœ—

The last call there blows up with this stack trace:

Error: This method is only meant to be run on single node. 0 found instead.
  at ReactWrapper.single (node_modules/enzyme/build/ReactWrapper.js:1065:17)
  at new ReactTestWrapper (node_modules/chai-enzyme/build/ReactTestWrapper.js:32:30)
  at wrap (node_modules/chai-enzyme/build/wrap.js:30:12)
  at Assertion.<anonymous> (node_modules/chai-enzyme/build/ChaiWrapper.js:136:42)
  at Assertion.Object.defineProperty.get (node_modules/chai/lib/chai/utils/overwriteProperty.js:50:37)
  at Context.<anonymous> (tests/chai-enzyme-repro.jsx:15:57)

Expected behavior for <textarea>?

Should you be able to use .value() to determine the value of a <textarea>?

expect( component.find( 'textarea' ) ).to.have.value( 'Hello world' );

ES6 style import results in test errors

Local chai-enzyme config

When configuring chai-enzyme globally I have failing tests, but if I add the following to the file with the failing tests it works:

import chai from 'chai'
import chaiEnzyme from 'chai-enzyme'
chai.use(chaiEnzyme())

Global chai-enzyme config

Importing chai-enzyme as a CommonJs module and configuring it globally works fine, but the ES6 style import causes tests to fail.

import chaiEnzymeEs6 from 'chai-enzyme' // Doesn't work
const chaiEnzyme = require('chai-enzyme') // Works fine

logging the export of each of these shows that chaiEnzymeEs6 === chaiEnzyme

Also, test fails in the same way when chai-enzyme is imported before stubbing the global window and document using js-dom.

Errors on failing tests

The errors I get in tests that are submitting a reduxForm, each failing due to some (related?) issue:

Invariant Violation: findComponentRoot(..., .10vfrs14k8w.1.1.1.0.1): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID ``.

Invariant Violation: processUpdates(): Unable to find child 1 of element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `.10vfrs14k8w.1.1.0.0`.

Invariant Violation: dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString for server rendering.

I have little knowledge about the internals of require vs ES6 imports, but something weird is going on there. Maybe someone else has some more insight.

have.prop checks on reference not equality

have.prop should check on object equality not reference equality.

When using immutable it becomes next to impossible to use reference equality because the object where it was set will be different where it is used.

`Contain` assertion passes when given non-node

It seems that the contain assertion does not check for the correct type of argument. For example, this will pass:

const wrapper = shallow(<Fixture />) 

expect(wrapper).to.contain("FooPony")

And:

const wrapper = shallow(<Fixture />) 

expect(wrapper).to.not.contain("FooPony")

will fail with:

TypeError: obj.indexOf is not a function
      at Assertion.include (node_modules/chai/lib/chai/core/assertions.js:221:45)
      at Assertion.assert (node_modules/chai/lib/chai/utils/addChainableMethod.js:83:49)

assertion of style() for shallow()/render()

I think there is bug (or perhaps a mis-documentation) of the style() assertion, namely that it only works if you mount() the component.

describe("Chai-enzyme style test", function() {

    it("should do style test on shallow component", function() {
        const component = (
                    <p style={{color:"red"}}>Hello, World</p>
        );
        const wrapper = shallow(component);
        expect(wrapper).to.have.style("color", "red");
    });

    it("should do style test on rendered component", function() {
        const component = (
            <p style={{color:"red"}}>Hello, World</p>
        );
        const wrapper = render(component);
        expect(wrapper).to.have.style("color", "red");
    });

    it("should do style test on mounted component", function() {
        const component = (
            <p style={{color:"red"}}>Hello, World</p>
        );
        const wrapper = mount(component);
        expect(wrapper).to.have.style("color", "red");
    });
});

Result is

Chai-enzyme style test
    โœ– should do style test on shallow component
    โœ– should do style test on rendered component
    โœ” should do style test on mounted component

Finished in 0.025 secs / 0.017 secs

SUMMARY:
โœ” 1 test completed
โœ– 2 tests failed

FAILED TESTS:
  Chai-enzyme style test
    โœ– should do style test on shallow component
      PhantomJS 2.1.1 (Mac OS X 0.0.0)
    Window is not a constructor (evaluating '(0, _cheerio2.default)(this.wrapper.html())')
    get@/Users/.../test.spec.js:38342:44 <- webpack:///~/chai-enzyme/build/ShallowTestWrapper.js:127:0
    style@/Users/.../test.spec.js:38276:19 <- webpack:///~/chai-enzyme/build/ShallowTestWrapper.js:61:0
    /Users/.../test.spec.js:37455:37 <- webpack:///~/chai-enzyme/build/assertions/generic.js:17:0
    /Users/...test.spec.js:37907:24 <- webpack:///~/chai-enzyme/build/ChaiWrapper.js:199:0
    /Users/.../test.spec.js:32360:31 <- webpack:///~/chai/lib/chai/utils/addMethod.js:41:0
    /Users/.../test.spec.js:78:50 <- webpack:///test.spec.js:16:38

    โœ– should do style test on rendered component
      PhantomJS 2.1.1 (Mac OS X 0.0.0)
    undefined is not a constructor (evaluating '_cheerio2.default.load(html)')
    render@/Users/.../test.spec.js:19762:33 <- webpack:///~/enzyme/build/index.js:61:0
    /Users/.../test.spec.js:88:43 <- webpack:///test.spec.js:25:31

expect(wrapper).to.contain() doesn't work for dangerouslySetInnerHTML

For this problem, I've tested both shallow and mount, the expect(wrapper).to.contain() cannot detect the rendered element from dangerouslySetInnerHTML.

For example, if I have a component like that:

return (
            <div>
                <p dangerouslySetInnerHTML={{ __html: `<a href="fake link">click it</a>` }} />
            </div>
        )```
The test: `expect(wrapper).to.contain(<a href="fake link">click it</a>);` cannot pass.

TypeError: Cannot read property 'value' of undefined on shallow component

Hi,

I'm using 0.5.2 and I have:

// In my setup.js ......
var chai = require("chai");

var chaiEnzyme = require('chai-enzyme');
chai.use(chaiEnzyme()); 

// In my test ......
import React from 'react';
import {shallow} from 'enzyme';
import { MyForm } from './my-form';

describe("\<MyForm>", () => {
  let wrapper = null;

  beforeEach(() => {
    const props = {
      csrf: {
        param: 'cool_csrf',
        token: '123456789'
      },
    };
    wrapper = shallow(<MyForm {...props}/>);
  });

  it("sets the CSRF token", () => {
    var field = wrapper.find('input[name="cool_csrf"]');
    expect(field.html()).to.contain('value="123456789"');
    expect(field).to.have.value('123456789');
  });
});

The first assertion works fine (i.e the it finds the input field okay), but I then get:

TypeError: Cannot read property 'value' of undefined
      at value (node_modules/chai-enzyme/build/assertions/value.js:13:23)
      at .<anonymous> (node_modules/chai-enzyme/build/ChaiWrapper.js:193:19)
      at ctx.(anonymous function) (node_modules/chai/lib/chai/utils/addMethod.js:41:25)
      at doAsserterAsyncAndAddThen (node_modules/chai-as-promised/lib/chai-as-promised.js:296:33)
      at .<anonymous> (node_modules/chai-as-promised/lib/chai-as-promised.js:255:21)
      at ctx.(anonymous function) [as value] (node_modules/chai/lib/chai/utils/overwriteMethod.js:49:33)
      at Context.<anonymous> (test/build/app/components/rails-form/webpack::29:1)

TypeError: not a function

Hello, guys. I was told here to use chai-enzyme to get the to.exist assertion working. Currently it just gives false positives, which is terrible, I think. I am just pasting here the last comment since it got not attention there:

I tried using chai-enzyme but had no luck:

import chai, {expect} from 'chai';
import chaiEnzyme from 'chai-enzyme';

chai.use(chaiEnzyme());

With that setup, every time I get a wrapper:

const wrapper = shallow(<ReceiptPage {...props} />);

... I get an error:

 TypeError: (0 , _enzyme2.default) is not a function

These are the versions I am using:

"chai": "3.5.0",
"chai-enzyme": "0.5.1",
"enzyme": "2.2.0",
"cheerio": "0.20.0",
"react": "15.0.2"

Can't run on [email protected]

Hi I update my react, react-dom, react-addons-test-utils to 15.4.0-rc.3, that the error occurs when I run npm test.

ERROR in .//react-element-to-jsx-string//react-addons-test-utils/index.js
Module not found: Error: Can't resolve 'react/lib/ReactTestUtils' in '/Users/Welly/Desktop/react-cool-starter/node_modules/react-element-to-jsx-string/node_modules/react-addons-test-utils'
@ .//react-element-to-jsx-string//react-addons-test-utils/index.js 1:17-52
@ .//react-element-to-jsx-string/index-dist.js
@ ./
/chai-enzyme/build/assertions/contain.js
@ ./~/chai-enzyme/build/index.js
@ ./tools/testing/test-bundler.js

Any solution for this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.