2017-07-04 75 views
0

我有以下時作出反應與debounceTime錯誤成分反應成分使用興農

探索在此輸入代碼

class IncrementalSearch extends React.Component { 

    constructor(props) { 
     super(props); 
     this.onSearch$ = new Subject(); 
     this.onChange = this.onChange.bind(this); 
    } 

    componentDidMount() { 
     console.log(this.simpleText); 
     this.subscription = this.onSearch$ 
      .debounceTime(300) 
      .subscribe(debounced => { 
       this.props.onPerformIncrementalSearch(debounced); 
      }); 
    } 

    componentWillUnmount() { 
     if (this.subscription) { 
      this.subscription.unsubscribe(); 
     } 
    } 

    onChange(e) { 
     const newText = e.target.value; 
     this.onSearch$.next(newText); 
    } 

    render() { 
     return (
      <div className={styles.srchBoxContaner}> 
       <input 
        className={styles.incSrchTextBox} 
        type="text" name="search" placeholder="Search.." 
        onChange={this.onChange} 
       /> 
      </div> 
     ); 
    } 
} 

我試圖測試這個使用酶,玩笑,和興農。我的單元測試看起來如下

it('calls componen`enter code here`tDidMount',() => { 

     const componentDidMountSpy = sinon.spy(IncrementalSearch.prototype, 'componentDidMount'); 
     const wrapper = mount(<IncrementalSearch />); 
     expect(IncrementalSearch.prototype.componentDidMount.calledOnce).toEqual(true); 
     componentDidMountSpy.restore(); 
    }); 

當我運行代碼,我得到以下錯誤

TypeError: this.onSearch$.debounceTime is not a function

at IncrementalSearch.componentDidMount (src/components/common/incrementalSearch/IncrementalSearch.jsx:37:13) at Function.invoke (node_modules/sinon/lib/sinon/spy.js:194:51)

但是如果我註釋掉debounceTime和其他東西不要通過。我該如何解決?

+0

是否有使用Sinon窺探被調用方法的具體原因? Jest有自己的spyOn方法: const spy = jest.spyOn(IncrementalSearch.prototype,'componentDidMount'); const wrapper = mount(); expect(spy).toHaveBeenCalled(); //或者其中一種方法... 修復您可能需要導入的實際問題或模擬rxJs – Grandas

回答

0

我剛纔添加下列導入和它的工作

import 'rxjs/add/operator/debounceTime'; 

我仍然不知道爲什麼,這並不在工作單元測試和工作當我運行的主要應用程序,但它的工作原理。

+1

該導入具有副作用,這意味着您不依賴其返回值,但對於它所具有的效果運行時間。這意味着如果您的代碼在您的應用中運行,那意味着您的應用中的某個位置正在運行該導入。當您單獨運行單個組件時,則不會運行整個應用程序,因此您不會執行導入代碼。 一般來說,這只是一種不聲明你的依賴的糟糕做法。如果你的單元依賴'debounceTime'作爲一個效用函數存在,那麼它也應該將它導入到模塊中。 – oligofren