Печать тестового документа с помощью enzyme — React

#reactjs #enzyme #stub

#reactjs #фермент #заглушка

Вопрос:

     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 в enzyme.

Я пробовал заглушать, как показано ниже, но это не работает.

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

Ответ №1:

Это не window.document.close то, что вызывается, а document.close метод включен printWindow .

Предпочтительно, чтобы на реальный DOM это вообще не влияло:

 const printWindowMock = {
  document: {
    write: sinon.stub(),
    ...
};

sinon.stub(window, 'open`).returns(printWindowMock);
  

Макеты должны восстанавливаться после каждого теста, поэтому их нужно выполнять в beforeEach и восстанавливать в afterEach . Это может быть автоматически обработано с помощью плагинов для тестирования фреймворка, таких как mocha-sinon .