Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme Jest window.getSelection() does not work

How to fix my situation? Jest + Enzyme testing of function below returns

TypeError: window.getSelection is not a function

My code:

    _addNewAgent () {
    window.getSelection().removeAllRanges();

    const newAgent = generateNewAgent();
    const newDataBase = this.state.agentsDatabase;

    newDataBase.push(newAgent);

    this.setState({
        currentAgentProfile: newAgent,
        agentsDatabase:      newDataBase,
        infoDisplayContent:  'profile'
    });
}

My test:

import React from 'react';
import { mount } from 'enzyme';
import App from '../containers/App';

const result = mount(
    <App />
);

test('add agent', () => {
const agentsList = result.state().agentsDatabase.length;

result.find('#addNewAgent').simulate('click');
expect(result.state().agentsDatabase.length).toBe(agentsList + 1);

expect(result.state().currentAgentProfile)
    .toEqual(result.state().agentsDatabase[agentsList]);

expect(result.state().infoDisplayContent).toBe('profile');
});
like image 691
Dmytro Zhytomyrsky Avatar asked Apr 28 '17 09:04

Dmytro Zhytomyrsky


1 Answers

You have to stub out window.getSelection().removeAllRanges(). I think this would work:

before(() => {
  window.getSelection = () => {
    return {
      removeAllRanges: () => {}
    };
  })
});
like image 60
Yangshun Tay Avatar answered Sep 23 '22 11:09

Yangshun Tay