简体   繁体   中英

Testing React-Router v1.0.0 href

Currently using Jest with React-Router to try and test an element has an href with the expected value.

from following the instructions here

jest.dontMock('../BasicPage')

describe('BasicPage', function() {
  let BasicPage = require('../BasicPage')
  let TestUtils = require('react-addons-test-utils')
  let ReactDOM = require('react-dom')
  let React = require('react')

  it('renders the Login button if not logged in', function() {
    let page = TestUtils.renderIntoDocument(<BasicPage />)
    let button = TestUtils.findRenderedDOMComponentWithTag(page, 'button')
    expect(ReactDOM.findDOMNode(button).textContent).toBe('Login')
  })

  it('renders the Account button if logged in', function() {
    let page = TestUtils.renderIntoDocument(<BasicPage authenticated={true} />)
    let button = TestUtils.findRenderedDOMComponentWithTag(page, 'button')
expect(ReactDOM.findDOMNode(button).getAttribute('href')).toBe('/admin')
  })
})

the element has a link like:

<Button bsStyle="primary"><Link to="/admin">Login</Link></Button>

when console.log'in the button the href isn't present and the test return null!

Has anyone found a way to get around this?

You need to render things under a <Router> instance if you want eg <Link> s to actually work. The <Router> provides the history instance on context that <Link> uses to generate href s and handle clicks.

For convenience in testing, we will let you render <Link> s without a history instance, but as you can see, they won't be functional.

expect(ReactDOM.findDOMNode(button).getAttribute('href')).toBe('/admin')

Isn't that finding the wrong thing? don't you want to find the anchor?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM