reactjs - 通过酶测试文档打印 - React
问题描述
const htmlString = ReactDOMServer.renderToStaticMarkup(printDetailsView(this.props.savedList));
/* istanbul ignore next */
setTimeout(() => {
const printWindow = window.open('', 'PRINT', `width=700,left=${left},top=${top}`);
/* istanbul ignore next */
printWindow.document.write(htmlString);
/* istanbul ignore next */
printWindow.document.close();
/* istanbul ignore next */
printWindow.focus();
/* istanbul ignore next */
printWindow.print();
/* istanbul ignore next */
printWindow.close();
}, 0);
我如何在酶中模拟 document.close()、document.write。
我尝试了像下面这样的存根,但它不起作用。
global.window.document.write = sinon.stub();
global.window.document.close = sinon.stub();
describe('FilterPanel Connected component testing', () => {
let wrapper;
let tokenGet;
let userStub;
before(() => {
tokenGet = sinon.stub(TokenProvider, 'get');
tokenGet.callsFake((key) => {
if (key === 'DP_FIRST_NAME') {
return 'Vini';
}
return null;
});
userStub = sinon.stub(User, 'isUserLoggedIn');
const deviceType = {
isDesktop: true,
};
wrapper = mount(
<FilterPanel
myListsDetails={myListsDetails}
savedListActions={savedListActions}
actions={actions}
deviceType={deviceType}
messagesTexts={messagesTexts}
store={storeFake(storeData)}
isShared={false}
openSlider={openSliderStub}
savedList={savedList} />);
});
after(() => {
shareListResetStub.reset();
getSavedListsGuestStub.reset();
tokenGet.resetHistory();
openSliderStub.reset();
userStub.resetHistory();
});
it('render FilterPanel', () => {
expect(wrapper.find('FilterPanel').length).to.equal(1);
});
it('Call print function', () => {
userStub.returns(true);
const instance = wrapper.instance();
instance.print();
});
it('Call print function', () => {
userStub.returns(true);
const instance = wrapper.instance();
wrapper.setProps({
savedList: { data: [] },
});
instance.print();
});
it('Dont print function since user is not logged in', () => {
userStub.returns(false);
const instance = wrapper.instance();
instance.print();
instance.checkAuth();
expect(openSliderStub.called).to.be.true;
});
});
解决方案
不是window.document.close
那个被调用,而是document.close
方法 on printWindow
。
Real DOM 最好完全不受影响:
const printWindowMock = {
document: {
write: sinon.stub(),
...
};
sinon.stub(window, 'open`).returns(printWindowMock);
每次测试后都应该恢复模拟,所以它们需要beforeEach
在afterEach
. 这可以通过测试框架插件自动处理,例如mocha-sinon
.
推荐阅读
- jquery - 为什么 SVG 对象的运动如此不可预测?
- android - 验证字符串是否同时包含英文和梵文字母
- python - OSMnx 没有“速度”属性
- javascript - 当数据改变时 v-bind 的值不会改变。Vue.js
- c# - 如何使用 Microsoft.Build.CentralPackageVersions?
- ios - 按下 UIBarButtonItem 时如何检测?
- flutter - 什么,何时以及如何在颤振中使用 MaterialTapTargetSize
- hyperledger-fabric - 见解 + 评估 gRPC 消息流 Hyperledger Fabric
- node.js - 在 Angular 的眼中了解 Node.js 版本的命令是什么(意见)?
- asp.net - 为什么我的网站在 azure 停止工作