酶 Jest window.getSelection() 不起作用
Enzyme Jest window.getSelection() does not work
如何解决我的情况? Jest + 下面功能的酶测试 returns
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');
});
你必须停止 window.getSelection().removeAllRanges()
。我认为这可行:
before(() => {
window.getSelection = () => {
return {
removeAllRanges: () => {}
};
})
});
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
对我来说,我也需要这个mock window.document.getSelection = jest.fn()
如何解决我的情况? Jest + 下面功能的酶测试 returns
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');
});
你必须停止 window.getSelection().removeAllRanges()
。我认为这可行:
before(() => {
window.getSelection = () => {
return {
removeAllRanges: () => {}
};
})
});
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
对我来说,我也需要这个mock window.document.getSelection = jest.fn()