2016-11-28 133 views
9

目前我手動初始化componentDidMount上的Quill編輯器,並且jest測試失敗。看起來像我在jsdom中得到的ref值是null。有和問題在這裏:https://github.com/facebook/react/issues/7371但看起來像裁判應該工作。任何想法我應該檢查?refs在Jest快照測試中爲null-react-test-renderer

組件:

import React, { Component } from 'react'; 
 
import logo from './logo.svg'; 
 
import './App.css'; 
 

 
class App extends Component { 
 

 
    componentDidMount() { 
 
    console.log(this._p) 
 
    } 
 
    
 
    render() { 
 
    return (
 
     <div className="App"> 
 
     <div className="App-header"> 
 
      <img src={logo} className="App-logo" alt="logo" /> 
 
      <h2>Welcome to React</h2> 
 
     </div> 
 
     <p className="App-intro" ref={(c) => { this._p = c }}> 
 
      To get started, edit <code>src/App.js</code> and save to reload. 
 
     </p> 
 
     </div> 
 
    ); 
 
    } 
 
}

測試:

import React from 'react'; 
 
import ReactDOM from 'react-dom'; 
 
import App from './App'; 
 
import renderer from 'react-test-renderer' 
 

 
it('snapshot testing',() => { 
 
    const tree = renderer.create(
 
     <App /> 
 
    ).toJSON() 
 
    expect(tree).toMatchSnapshot() 
 
})

其結果是,輸出的console.log空。但我希望P標記

+0

請將相關代碼直接添加到問題中。 – Timo

回答

23

由於測試渲染器沒有耦合到React DOM,它不知道什麼樣的引用應該看起來像。 React 15.4.0增加了爲測試渲染器模擬參考的功能,但您應該自己提供這些模擬React 15.4.0 release notes包括這樣做的一個例子。

import React from 'react'; 
import App from './App'; 
import renderer from 'react-test-renderer'; 

function createNodeMock(element) { 
    if (element.type === 'p') { 
    // This is your fake DOM node for <p>. 
    // Feel free to add any stub methods, e.g. focus() or any 
    // other methods necessary to prevent crashes in your components. 
    return {}; 
    } 
    // You can return any object from this method for any type of DOM component. 
    // React will use it as a ref instead of a DOM node when snapshot testing. 
    return null; 
} 

it('renders correctly',() => { 
    const options = {createNodeMock}; 
    // Don't forget to pass the options object! 
    const tree = renderer.create(<App />, options); 
    expect(tree).toMatchSnapshot(); 
}); 

請注意,它只能與之反應15.4.0及更高

+0

感謝您的評論。我的用例是,一旦組件被安裝,我想要在DOM元素內渲染Quill編輯器。我可能會返回像document.createElement(「div」)。但在這種情況下,渲染的部分不會成爲快照測試的一部分。有沒有辦法包含它? – user3718704

+2

使用測試渲染器進行快照測試不適用於DOM依賴部件。如果您需要測試DOM本身而不是React組件,請考慮在jsdom環境中使用Enzyme's mount()。 –

+0

感謝您分享此答案,這正是我期待的。 –