2016-11-29 68 views
2

我正在使用酶,sinon,並期望單元測試我的反應組分。如何sinon窺探一個React組件的構造函數 - 單元測試?

import React from 'react'; 
import expect from 'expect.js'; 
import { shallow } from 'enzyme'; 

import ExampleComponent from './../../../src/js/components/example-component'; 

describe('Test <ExampleComponent />', function() { 

beforeEach(function() { 
    this._sandbox = sinon.sandbox.create(); 
    this.constructorSpy = this._sandbox.spy(ExampleComponent.prototype, 'constructor'); 
}); 

afterEach(function() { 
    this._sandbox.restore(); 
    this.constructorSpy = null; 
}); 

it('Should set the state with the correct data [constructor]', function() { 
    const wrapper = shallow(<ExampleComponent />); 
    console.log(' - callCount: ', this.constructorSpy.callCount); 
    expect(this.constructorSpy.calledOnce).to.be(true); 

    expect(Immutable.is(wrapper.state('shownData'), Immutable.Map())).to.be(true); 
}); 

我在組件構造函數中設置了一些邏輯,它根據我傳入的道具來設置狀態。然而,這個測試不斷告訴我,構造函數調用計數是0,並且它不被調用。

窺探組件構造函數的正確方法是什麼?我究竟做錯了什麼?

我正在使用沙盒,因爲我還想添加其他功能以添加到沙箱中以供將來窺探。

回答

3

當酶淺呈現測試時,應該自動調用構造函數(以及任何其他生命週期方法)。嘗試在測試中覆蓋它可能會非常複雜,而且對於您要檢查的內容而言並非必要。

如果構造函數正在設置基於道具的狀態,爲什麼檢查測試中的結果狀態不夠? (請參閱下面的示例中的'非常重要'斷言)

另一種選擇:假定您將設置的項目設置爲組件渲染中使用的狀態 - 在這種情況下,您可以在渲染中檢查這些項目元件。

最後,我還包括在構造函數調用,我再測試(使用興農)斷言,它被稱爲窺視,如果它是有幫助的。

例陣營組成:

import React, { Component, PropTypes } from 'react' 

export default class Post extends Component { 
    static propTypes = { 
    markRead: PropTypes.func.isRequired, 
    postName: PropTypes.string.isRequired 
    } 

    constructor (props) { 
    super(props) 
    const { markRead, postName } = props 

    markRead() 
    this.state = { 
     postName: 'Very Important: ' + postName 
    } 
    } 

    render() { 
    const { postName } = this.state 

    return (
     <div className='post-info'> 
     This is my post: {postName}! 
     </div> 
    ) 
    } 
} 

實例酶試驗,所有經過:

import React from 'react' 
import assert from 'assert' 
import { shallow } from 'enzyme' 
import { spy } from 'sinon' 

import Post from 'client/apps/spaces/components/post' 

describe('<Post />',() => { 
    const render = (props) => { 
    const withDefaults = { 
     markRead:() => {}, 
     postName: 'MyPostName', 
     ...props 
    } 
    return shallow(<Post {...withDefaults} />) 
    } 

    it('renders and sets the post name',() => { 
    const markReadSpy = spy() 
    const props = { 
     markRead: markReadSpy 
    } 
    const wrapper = render(props) 
    const postInfo = wrapper.find('.post-info') 
    const postText = postInfo.text() 

    assert.equal(wrapper.state('postName'), 'Very Important: MyPostName') 
    assert(markReadSpy.calledOnce) 
    assert.equal(postInfo.length, 1) 
    assert(postText.includes('MyPostName')) 
    }) 
}) 

注:另外,它看起來好像你是不是在你上面的例子供參考進口興農。