我最近为反应组件编写了一个测试,点击按钮后将窗口滚动到顶部。
我编写的测试文件在NodeJS 6.9上没有错误,不幸的是,当我升级到NodeJS 7.4时,我开始收到标题中提到的错误。
我花了两天的时间阅读和尝试各种方法/调试问题,但我是石头围墙。任何帮助非常感谢。
此问题的所有其他相关但不必要的内容可以在其回购中看到: https://github.com/dirtyredz/react-scroll-up-button
test.js
import { jsdom } from 'jsdom';
var exposedProperties = ['window', 'navigator', 'document'];
global.document = jsdom('<!doctype html><html><body style="height:2000px"></body></html>');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
require('raf').polyfill()
import React from 'react';
import { mount } from 'enzyme';
import sinon from 'sinon';
import TestUtils from 'react-addons-test-utils';
import ScrollUpButton from '../react-scroll-up-button';
import { expect } from 'chai';
//Testing group
describe('Testing <ScrollUpButton/> Action scroll to default top:', ()=>{
let Component, ScrollTo_Stub;
before(()=>{
window.pageYOffset = 0
//Render component
Component = mount(<ScrollUpButton />);
//Settup stub and replace scrollTo function with ours.
// TypeError: Attempted to wrap scrollTo which is already stubbed
ScrollTo_Stub = sinon.stub(window, 'scrollTo').callsFake((x,y)=>{
window.pageXOffset = x;
window.pageYOffset = y;
Component.instance().HandleScroll(); // <-- call HandleScroll so the test can simulate the button being toggled
});
})
after(()=>{
ScrollTo_Stub.restore(); // <-- Restore the objects method
//window.scrollTo.restore(); // <-- Restore the objects method
})
//did it scroll the page up
it('did scroll the page to 0', (done) => {
expect(Component.state().ToggleScrollUp).to.equal(''); // <-- Is the button hidden
window.pageYOffset = 300 // <-- scroll window down to prepare for smulation
Component.instance().HandleScroll(); // <-- call handleScroll since we scrolled the window down.
expect(Component.state().ToggleScrollUp).to.equal(true); // <-- Is the button visible
Component.instance().HandleClick(); // <-- call HandleClick to start the scroll up simulation.
//Well wait a little bit to let the simulation complete
setTimeout(()=>{
expect(ScrollTo_Stub.lastCall.args[1]).to.within(-10,10); // <-- is pageYOffset between -10 and 10
expect(Component.state().ToggleScrollUp).to.equal(''); // <-- Button should be hidden again
done() // <-- since were asynchronous with setTimeout instruct chai that were done with the test.
}, 500);
});
});
临时修复帮助
请任何人解释为什么这有效,如果有更好的方法来实现这一点。
在JS文件中的FIRST stub()
之前调用它将允许所有后续存根按预期工作。
window.scrollTo = null;
我在此行之前和此行之后有一个consoled.log window.scrollTo。结果完全一样。所以我不知道为什么这会使代码工作。