Enzyme Jest window.getSelection() does not work
Asked Answered
I

3

17

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');
});
Ity answered 28/4, 2017 at 9:41 Comment(0)
L
17

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

before(() => {
  window.getSelection = () => {
    return {
      removeAllRanges: () => {}
    };
  })
});
Learn answered 28/4, 2017 at 10:54 Comment(3)
Worked for me. Thanks. As I found 'window' in jest does not support getSelection(). github.com/tmpvar/jsdom/issues/321Ity
Update your answer. jsdom@16 now supports selection apis and there is no need to mock them.Sebi
@Sebi You seem like you know what to update. In the spirit of collaboration on Stack Overflow, could you help with updating it? I haven't touched these stuff in over 2 years and am not confident I will be updating it correctly.Learn
B
9

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
Barratry answered 23/7, 2020 at 23:33 Comment(1)
Thanks for you answer, I found that Jest release version 26 that now use jsdom@16. So just need to use latest Jest version to fix the issue. See: github.com/facebook/jest/blob/master/CHANGELOG.mdAshleyashli
J
2

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

Jeannettejeannie answered 25/2, 2022 at 16:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.