2017-06-19 59 views
1

首先我要讓知道,我是新來的測試與反應,並希望確認,如果我寫正確的測試。被內部調用模擬功能反應成分渲染功能

我有一個陣營組件是這樣的 -

import React, { Component } from "react"; 

class DemoComponent extends Component 
{ 
    returnSomething() 
    { 
     return "something"; 
    } 

    render(){ 
     return(
      <div>{ this.returnSomething() }</div> 
     ); 
    } 
} 

和我寫測試,以驗證方法調用是這樣的 -

import React from "react"; 
import { shallow } from "enzyme"; 
import DemoComponent from "./DemoComponent.js"; 

const component = shallow(<DemoComponent/>); 

test('"returnSomething" method is called when the component is rendered',() => { 
    component.instance().returnSomething= jest.fn(); 
    component.update(); 
    component.instance().render(); 
    expect(component.instance().returnSomething).toHaveBeenCalled(); 
}); 

測試運行正常,但我想知道如果我寫的測試是正確的方法。

+0

你能解釋一下你爲什麼要考這樣的組件,而不是使用酶和快照? https://medium.com/@gethylgeorge/testing-a-react-redux-app-using-jest-and-enzyme-b349324803a9 –

+0

我使用'enzyme'。我只發佈了一部分代碼。可能是爲了方便,我應該更新代碼。 @AndreasKöberle – besrabasant

+0

爲什麼你不在測試中使用它? 'expect(component).toMatchSnapshot()'會測試渲染方法的結果。您是否知道快照功能? –

回答

2

您能在這裏寫一個測試通過,所以我沒有看到一個問題。

只是測試該組件上的一些方法被調用並沒有真正告訴你的render()結果什麼 - 組件如何呈現。作爲安德烈亞斯指出,測試render()的快照可能是更好的(假設你使用玩笑) - 你正在測試這種方式,實際的渲染結果,而不是隻檢查一些方法是否接到電話時呈現。或者,您可以使用.matchesElement()之類的東西,或者檢查單個屬性以創建更強大的測試。

+0

是的,我研究了快照測試,他們非常值得。使用'snapshots'後,我的測試斷言得到了改善。 – besrabasant