【问题标题】:React component with debounceTime errors when using Sinon使用 Sinon 时反应组件出现 debounceTime 错误
【发布时间】:2017-12-07 08:50:09
【问题描述】:

我有以下 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 不是函数

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

但是,如果我注释掉 debounceTime 并保留它通过的所有其他内容。我该如何解决这个问题?

【问题讨论】:

  • 使用Sinon监视被调用的方法是否有特定的原因? Jest 有自己的 spyOn 方法: const spy = jest.spyOn(IncrementalSearch.prototype, 'componentDidMount'); const wrapper = mount();期望(间谍).toHaveBeenCalled(); // 或者其中一种方法...要解决实际问题,您可能需要导入或模拟 rxJs

标签: reactjs sinon enzyme jestjs


【解决方案1】:

我刚刚添加了以下导入并且它起作用了

import 'rxjs/add/operator/debounceTime';

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

【讨论】:

  • 该导入有副作用,这意味着您不依赖于它的返回值,而是依赖于它对运行时的影响。这意味着如果您的代码在您的应用程序中工作,那么这意味着您的应用程序中的某个地方正在运行该导入。当您单独运行单个组件时,您不会运行整个应用程序,因此您不会运行执行导入的代码。一般来说,这只是一种不声明依赖项的糟糕做法。如果你的单元依赖debounceTime作为一个实用函数存在,那么它也应该在模块中导入它。
猜你喜欢
  • 2022-07-08
  • 2014-02-23
  • 2021-07-18
  • 2018-07-18
  • 2021-09-07
  • 2019-03-01
  • 2021-08-16
  • 1970-01-01
  • 2021-10-03
相关资源
最近更新 更多