2016-11-07 23 views
0

我有一個簡單的測試:等待酶和玩笑條件(最終一致性,有超時斷言)

import React from 'react'; 
import GenericButton from 'components/buttons/GenericButton'; 
import { shallow } from 'enzyme'; 
import { shallowToJson } from 'enzyme-to-json'; 

describe('Generic Button',() => { 
    test('Button action called when clicked',() => { 
     var clicked = false; 
     const component = shallow(
      <GenericButton action={() => { 
       clicked = true; 
      }} 
      id="testComponent"/> 
     ); 

     component.find('testComponent').first().simulate('click'); 
     expect(clicked).toBeTruthy(); 
    }); 
}); 

但是作爲動作最終做到了這一點將會失敗,

如果我設置斷言最終會發生(例如使用的setTimeout),將工作

但它會更好,如果我做的斷言(發現這個使用茉莉花例子)之前以下

東西210
 waitsFor(() => { 
      return clicked; 
     }, "the value to change", 1000); 

什麼是酶/笑話等價的呼籲?


編輯:成分的含量

render() { 
    return <Button id={this.props.id} 
        key={this.props.id} 
        onClick={() => this.props.action()} 
        bsStyle={this.props.style}> 
       {this.props.text} 
      </Button>; 
} 

(巴頓是一個第三方庫組件)

+0

在一個單位,你不應該需要這個。你能發佈你想測試的代碼嗎? –

+0

我確保在上述情況下點擊按鈕的動作。 – mangusbrother

+0

當然,但是'component.find('testComponent')。first()。simulate('click');'運行時發生的唯一事情就是找到'onClick'屬性並調用它,所以沒有這種方式在每次測試中都不起作用。由於沒有涉及真正的DOM,這只是一個函數調用。所以'waitsFor'唯一的用例就是當你在一個真正的或無頭的瀏覽器中運行接受程序。但是,當你使用Jest時,情況並非如此。 –

回答

1

要測試是否已正確添加一個單擊處理程序傳遞一個間諜到您的評論,模擬點擊並檢查是否調用了間諜。這樣做不需要使用waitsFor

import React from 'react'; 
import GenericButton from 'components/buttons/GenericButton'; 
import { shallow } from 'enzyme'; 
import { shallowToJson } from 'enzyme-to-json'; 

describe('Generic Button',() = > { 
    test('Button action called when clicked',() = > { 
    const action = jest.fn(); 
    const component = shallow(
     <GenericButton action={action} 
      id="testComponent"/> 
    ); 
    component.find('Button').first().simulate('click'); 
    expect(action).toHaveBeenCalled(); 
    }); 
}); 
+0

由於時間原因,這仍然失敗。在期待被調用的時候,該行爲將不會被調用。 (我認爲這是由於調用的異步性質造成的) – mangusbrother

+0

您可以發佈組件中調用操作的代碼,因爲這裏沒有涉及異步,這是所有同步,因爲沒有真正的瀏覽器在運行。 'simulate'只是從組件中獲取'onClick'屬性並調用函數。 –

+0

添加了它。問題 – mangusbrother