2017-02-20 58 views
4

我需要測試fetchData()函數。我一直在嘗試遵循this(以及其他許多)教程,並試圖讓它在過去的3個小時內與我的功能一起工作,但目前爲止還沒有運氣。我最好還是想以另一種方式來做,因爲我不認爲jQuery和React應該一起使用。測試調用API的函數

我基本上想檢查是否1)當提交搜索表單(SearchForm中的按鈕被點擊)時調用該函數並且2)檢查數據是否返回。

有沒有人有關於如何開始的建議?

感謝

首頁

export default class Home extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     value: '', 
     loading: false, 
     dataError: false 
    } 
    this.nodes = []; 
    this.fetchData = this.fetchData.bind(this); 

    } 
    fetchData(e) { 
    e.preventDefault(); 
    this.setState({loading: true}); 
    axios.get(`https://api.github.com/search/repositories?q=${this.state.value}`) 
    .then(res => { 
     this.nodes = res.data.items.map((d, k) => <RepoItem {...d} key={k}/>); 
     this.setState({loading: false}); 
    }) 
    .catch(err => { 
     this.setState({dataError: true}); 
    }); 
    } 
    render() { 
    return (
     <div className="home-wrapper"> 
     <SearchForm value={this.state.value} 
        onSubmit={this.fetchData} 
        onChange={(e) => this.setState({value: e.target.value})}/> 
     {this.state.loading ? 
     <Spinner/>: 
     !this.state.dataError ? this.nodes : 
     <h1>Oops! Something went wrong, please try again!</h1>} 
     </div> 
    ); 
    } 
} 

RepoItem

export const RepoItem = props => (
    <div className="repo-item"> 
    <h1>{props.full_name}</h1> 
    </div>); 
+0

不確定測試部分,但您可能想要將'this'綁定到您的fetchData函數,所以其中的this.setState引用Home部件。 – Mateusz

+0

編輯:nvm我已經擁有了它,我只是刪除了一些虛擬的組件。雖然謝謝! – Apswak

+0

嗯不知道爲什麼它的作品,但基本上,如果你在你的函數中引用它,然後將它傳遞給另一個組件,而不綁定'this'(在你的例子中是SearchForm),'this'將在調用時引用該組件,在SearchForm中更新狀態,而不是Home。在你的例子中,你可以使用onChange事件的箭頭函數來自動綁定到Home組件,所以this.setState({value:e.target.value}正確地更新你的Home組件的狀態。 – Mateusz

回答

2
  1. 要檢查功能,當表單提交時調用,您可以淺呈現<SearchForm>組件與spy功能通過作爲onSubmit道具。模擬submit事件並檢查是否調用了spy函數。
  2. 要檢查數據是否返回,請模擬axios服務。您可以使用this library來模擬axios呼叫。撥打fetchData(),看看this.nodes和狀態是否正確更新。

    const wrapper = shallow(<Home />); 
    wrapper.instance().fetchData().then(() => { 
        ... your assertions go here ... 
    }) 
    

我認爲這是永遠是最好的做法,從那裏異步動作發生的方法返回一個Promise對象或任何可鏈接的對象。