Javascript - Невозможно использовать оператор импорта вне модуля - PullRequest
0 голосов
/ 09 марта 2020

Итак, у меня есть серьезная проблема с импортом из одного класса в другой, и я сделал это в своем «основном» классе, который я называю

detailsPage. js

import { DetailsPage } from '../tests/detailsPageObj';

const utils = require("../utils/utils");
const assert = require('../node_modules/chai').assert;
const userData = require('../globalContent.json');

describe('Details page', function () {
    const detailsPage = new DetailsPage();

    // The details page is accessible by the specified URL
    it(`Is defined by the URL: ${userData.url}`, async function () {
        await detailsPage.navigate();
    });

    // Details page has a form and it can be filled out with user data
    it('Has a form that can receive user data', async function () {
        await detailsPage.fillFormWithUserData(); // If you want, make the user data passable to the method
        await utils.click(detailsPage.form.buttons.nextStep);
    });

    if (detailsPage.hasStockConflict) {
        // Details page allows the user to fix conflicts in stocks
        it('Enables resolution of stock conflicts', async function () {
            // Wait for stock to fully load
            await browser.sleep(2000);
            await detailsPage.clickAllRemoveButtons();
            await detailsPage.clickAllDecreaseButtons();
        });
    }

    // Details page allows the user to proceed to the next stage when all conflicts (if any) has been resolved
    it('Allows the user to proceed to the next stage of purchasing', async function () {
        const nextStepButton = detailsPage.form.buttons.nextStep;
        await utils.elementToBeClickable(nextStepButton);
        await utils.click(nextStepButton);
    });
});

и сейчас я пытаюсь получить DetailsPage из другого скрипта, который называется:

detailsPageObj

import { element, by } from 'protractor';

const utils = require("../utils/utils");
const userData = require('../globalContent.json');

export class DetailsPage {
    get pageUtils() {
        return {
            qtyRegex: /^Sorry.*?(\d+)/
        }
    }

    private get fields() {
        return {
            email: element(by.id('email')),
            firstName: element(by.id('firstName')),
            lastName: element(by.id('lastName')),
            postalCode: element(by.id('postalCode')),
            addressOne: element(by.id('addressOne')),
            addressTwo: element(by.id('addressTwo')),
            phone: element(by.id('phone')),
            businessCustomerCB: element(by.id('isBusinessCustomer')),
            company: element(by.id('company')),
            GST: element(by.id('gst')),
        }
    }

    private get groups() {
        return {
            address: element(by.css('div#addressGroup.input-container.showHiddenGroup'));
            company: element(by.id('companyGroup')),
        }
    }

    private get modals() {
        return {
            contactModalLink: element(by.id('contactModalLink')),
            cross: element(by.className('modal-cross')),
        }
    }

    private get formButtons() {
        return {
            nextStep: element(by.id('submitIdentityFormButton')),
            mobile: this.mobileFormButtons
        }
    }

    private get mobileFormButtons() {
        return {
            continue: element(by.id('stock-conflict-continue-button')),
            removeOutOfStockItems: element(by.css('button[id="removeOutOfStockItems"]')), // I just assumed that this is a part of the form
        }
    }

    private get productFrameMobileButtons() {
        return {
            stockControll: element.all(by.className('stock-controller mobile')),
            remove: element.all(by.className('btn btn-remove btn-outlined mobile')),
        }
    }

    private get productFrameDesktopButtons() {
        return {
            stockControll: element.all(by.className('stock-controller desktop')),
            remove: element.all(by.className('btn btn-remove btn-outlined desktop')),
        }
    }

    get form() {
        return {
            fields: this.fields,
            groups: this.groups,
            buttons: this.formButtons,
            modals: this.modals
        }
    }

    get productFrame() {
        return {
            buttons: {
                decrease: element.all(by.className("btn left")).first(),
                mobile: this.productFrameMobileButtons,
                desktop: this.productFrameDesktopButtons
            }
        }
    }

    get errors() {
        return {
            stockConflict: element(by.className('generic-error-heading')),
        }
    }
}

и что я я пытаюсь сделать это в detailsPage. js я пытаюсь импортировать detailsPageObj. js, но всякий раз, когда я пытаюсь это сделать, я получаю SyntaxError: Cannot use import statement outside a module.

Что я делаю неправильно

1 Ответ

1 голос
/ 09 марта 2020

Я не знаю, как выглядит ваша среда, но я столкнулся с подобной проблемой, когда моя среда использовала полный шаг сборки для создания целевого кода JS из моих источников (например, из TypeScript или из ES6 +) в пакет / plain JS.

Но тогда в моей тестовой среде не было никакого шага сборки. Поэтому, когда я выполнял тесты, он понимал только обычный JS, который по умолчанию в среде node.js не распознает import, а только require.

. Вы можете использовать import в своем node.js код без шага сборки, но вам нужно выполнить некоторые шаги, например, переименовать файл с *. js на * .m js. Подробнее здесь .

...