2016-05-29 42 views
0

你能說出爲什麼這個Jest測試與ReactJS失敗?我想測試我的頂級陣營組件AppJest找不到ReactJS

錯誤: 運行時錯誤 - 不變違規:_registerComponent(...):目標容器不是一個DOM元素。 在不變(node_modules /反應/ node_modules/FBJS/LIB/invariant.js:38:15)

app.js

// ./app.js 
var React = require('react'); 
var ReactDOM = require('react-dom'); 

import Howdy from './app/Howdy'; 


export default class App extends React.Component { 
    render() { 
    return (
     <div> 
     Hello 
     </div> 
    ); 
    } 
}; 

ReactDOM.render(
    <App />, 
    document.getElementById('app') 
); 

APP-test.js

// __tests__/app-test.js 

jest.unmock('../app'); 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import TestUtils from 'react-addons-test-utils'; 
import App from '../app'; 


describe('Test App Component',() => { 

    it('sample test...',() => { 
    const myApp = TestUtils.renderIntoDocument(
     <App /> 
    ); 

    const myAppNode = ReactDOM.findDOMNode(myApp); 

    expect(myAppNode.isElement).toEqual(true); 
    }); 
}); 
+1

註釋出ReactDOM.render()中app.js. –

+0

但是這是我的主要應用程序模塊,我想我可以將'App.js'導入另一個只有調用'ReactDOM.render()'的.js文件。我會嘗試並報告結果:-) –

+0

習慣上導入頂級組件,因此在那裏沒有什麼可測試的。你仍然可以測試直JavaScript。只是不與renderIntoDocument。 –

回答

0
const myApp = TestUtils.renderIntoDocument(
    <App /> 

使用let代替上述塊中的const

const means that the identifier can’t be reassigned. (Not to be confused with immutable values. Unlike true immutable datatypes such as those produced by Immutable.js and Mori, a const object can have properties mutated.) If I don’t need to reassign, const is my default choice over let because I want the usage to be as clear as possible in the code. I use let when I need to reassign a variable. Because I use one variable to represent one thing, the use case for let tends to be for loops or mathematical algorithms. I don’t use var in ES6. There is value in block scope for loops, but I can’t think of a situation where I’d prefer var over let .

ref