繁体   English   中英

reactjs在使用Jasmine进行测试时获取``未定义不是函数''

[英]reactjs get `undefined is not a function` on testing with Jasmine

我有一个React组件。 我想测试一下。 但是,每次尝试使用已测试的组件来findRenderedDOMComponentWithTag ,我都会遇到意外错误。 这是Karma错误日志:

05 09 2015 20:31:23.450:INFO [watcher]: Changed file "/tmp/35ffb917aab483a567d1be6fed779291.browserify".
PhantomJS 2.0.0 (Linux 0.0.0) DestroySession should process user logout FAILED
    TypeError: undefined is not a function (evaluating 'target.dispatchEvent(e)') in http://localhost:9876/karma.js (line 1134)
        at /tmp/35ffb917aab483a567d1be6fed779291.browserify:59730:16
PhantomJS 2.0.0 (Linux 0.0.0): Executed 3 of 7 (1 FAILED) (skipped 4) (0.04 secs / 0.019 secs)

我的堆栈是:

  • CoffeeScript的
  • 反应(+ JSX)
  • browserify
  • karma.js
  • phantomjs
  • 茉莉

零件:

React = require('react')
ReactBootstrap = require('react-bootstrap')

Button = ReactBootstrap.Button

SessionActions = require('../../actions/session_actions.coffee')

module.exports = React.createClass
  contextTypes: router: React.PropTypes.func
  handleClick: (e) ->
    e.preventDefault()
    console.log 'хуйло'
    SessionActions.destroy()
    @context.router.transitionTo('/sessions/new')
  render: ->
    <Button onClick={@handleClick} className='btn btn-default navbar-btn'>Sign out</Button>

测试:

React = require('react/react-with-addons.js')
TestUtils = React.addons.TestUtils

DestroySession = require('../../../../app/coffee/components/sessions/destroy.coffee')

describe 'DestroySession', ->
  instance = undefined

  beforeEach ->
    instance = TestUtils.renderIntoDocument(<DestroySession />)


  it 'should process user logout', ->
    localStorage.setItem('token', 123)
    localStorage.setItem('userName', 'Anonymous Person')
    localStorage.setItem('userId', 11)

    button = TestUtils.findRenderedDOMComponentWithTag(instance, 'button')

    console.log button

这很奇怪,但是当我尝试console.log我的button变量时出现错误。 如果我注释掉测试的最后一行,它将通过。 发生了什么?

您需要调用getDOMNode()

console.log button.getDOMNode()

注意 :这在0.14.2中进行了更改,其中TestUtils.find / scry方法将直接返回DOM节点。

这可能不是正确的答案,但由于我在茉莉花中得到了完全相同的异常,所以我登陆了这里,并且我发现了导致它的原因,所以我将其留在这里:

我犯的错误是不小心将全局文档保存在对象内部,而不是将局部变量保存为document

/*
var document = {
   parentId: parentItem._id, 
   childIds: [childItem._id],
};
I had moved the above elsewhere, so "document" now refers to window.document
*/
db.saveInIndex(parentId, document);

然后打电话给这个:

console.log(db.getFromIndex(parentId));

结果是这样的:

TypeError: undefined is not a function (evaluating 'target.dispatchEvent(e)')

因为它试图记录看起来像这样的对象:

{
  parentId: 'HA89A8S98A98',
  document: <<< the global "document" - not what we wanted! >>>
}

该全局var 文档通常是页面的HTML内容,但是当您针对PhantomJS运行测试时,您会得到它的解释!

(针对Chrome浏览器运行Karma的情况有所不同)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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