Dmytro Zhytomyrsky
Dmytro Zhytomyrsky

Reputation: 1401

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

Upvotes: 17

Views: 12594

Answers (3)

lehanh
lehanh

Reputation: 585

for me, I also need this mock window.document.getSelection = jest.fn()

Upvotes: 2

Bruno Monteiro
Bruno Monteiro

Reputation: 4519

2020 Update

I was struggling with this as well and @Mohammad comment pointed me in the right direction, so I decided to add that as an answer here to help others:

As mentioned by @Mohammad, jsdom is now on version 16, which supports getSelection. However, Jest@25 is still using older versions of jsdom, so what you can do is use this NPM package to "by pass" that:

https://www.npmjs.com/package/jest-environment-jsdom-sixteen

After the install, just update your Jest config to use this:

{
  "testEnvironment": "jest-environment-jsdom-sixteen"
}

Or, use it as a flag direct in the NPM command:

npm run test --env=jsdom-sixteen

Upvotes: 9

Yangshun Tay
Yangshun Tay

Reputation: 53169

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

before(() => {
  window.getSelection = () => {
    return {
      removeAllRanges: () => {}
    };
  })
});

Upvotes: 17

Related Questions