0
votes

I have the following React component

explore enter code here

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

I am trying to test this using Enzyme, Jest, and Sinon. My unit test looks like the following

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

When I run the code I get the following error

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)

However if I comment out the debounceTime and leave everything else it passes. How do I fix this?

1
Is there a specific reason for using Sinon to spy on method being called? Jest has a spyOn method of its own: const spy = jest.spyOn(IncrementalSearch.prototype, 'componentDidMount'); const wrapper = mount(< IncrementalSearch />); expect(spy).toHaveBeenCalled(); // Or one of the methods... To fix the actual issue you might need to import or mock rxJs - Grandas

1 Answers

0
votes

I just added the following import and it worked

import 'rxjs/add/operator/debounceTime';

I still do not know why this does not work in unit tests and works when I am running the main app, but it works.