Jest.js 使用Sinon时React组件出现debounceTime错误

vh0rcniy  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(104)

我有以下React组件

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>
        );
    }
}

我正在尝试使用Enzyme,Jest和Sinon来测试这个。我的单元测试如下所示

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不是函数
at IncrementalSearch.componentDidMount(src/components/common/incrementalSearch/IncrementalSearch.jsx:37:13)at Function.invoke(node_modules/sinon/lib/sinon/spy.js:194:51)
但是,如果我注解掉debounceTime并留下其他所有内容,它就会通过。我该如何解决此问题?

afdcj2ne

afdcj2ne1#

我只是添加了以下导入,它的工作

import 'rxjs/add/operator/debounceTime';

我仍然不知道为什么这在单元测试中不起作用,而在我运行主应用程序时起作用,但它起作用了。

相关问题