【问题标题】:Enzyme Jest window.getSelection() does not work酶玩笑 window.getSelection() 不起作用
【发布时间】:2017-09-26 09:14:41
【问题描述】:

如何解决我的情况?下面函数的 Jest + Enzyme 测试返回

TypeError: window.getSelection is not a function

我的代码:

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

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

    newDataBase.push(newAgent);

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

我的测试:

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

【问题讨论】:

    标签: reactjs testing jestjs bdd enzyme


    【解决方案1】:

    你必须删除window.getSelection().removeAllRanges()。我认为这会起作用:

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

    【讨论】:

    • 为我工作。谢谢。正如我在玩笑中发现的“窗口”不支持 getSelection()。 github.com/tmpvar/jsdom/issues/321
    • 更新你的答案。 jsdom@16 现在支持选择 api,无需模拟它们。
    • @Mohammad 您似乎知道要更新什么。本着 Stack Overflow 上的协作精神,您能帮忙更新一下吗?我已经 2 年多没有碰过这些东西了,我不确定我会正确更新它。
    【解决方案2】:

    2020 年更新

    我也在为此苦苦挣扎,@Mohammad 的评论为我指明了正确的方向,所以我决定在此处添加它作为答案以帮助其他人:

    正如@Mohammad 所提到的,jsdom 现在是版本 16,它支持getSelection。但是,Jest@25 仍在使用旧版本的jsdom,所以你可以做的是使用这个 NPM 包来“绕过”:

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

    安装后,只需更新您的 Jest 配置即可使用:

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

    或者,直接在 NPM 命令中使用它作为标志:

    npm run test --env=jsdom-sixteen
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-11
    • 2023-03-27
    • 2021-01-26
    • 2018-10-13
    • 2021-04-18
    • 2018-08-25
    • 2023-01-07
    • 1970-01-01
    相关资源
    最近更新 更多