Steerpike
Steerpike

Reputation: 1853

Sharing a Constant value between two Javascript files

I'm new to JS and Node in general. I'm trying to use Puppeteer to simply get the text value of a

tag and save it to a constant. I'm then trying to use the value in a 'base' class (index.js) where my Mocha tests live. For some reason, I'm struggling. I'm using async.

My file structure is:

enter image description here

Here is my Puppeteer script:

//customerChoices.js
module.exports = async(page) => {

  const frame = page.frames().find(frame => frame.name() === 'iframe');

  const saveYourChoicesButton = await frame.$('body > div > div > div > form > footer > div > button.permissions-block__submit');
  await saveYourChoicesButton.click({});

  await page.waitForSelector('.page-title');
  const confirmationMessageText = await frame.$eval('.submission-response__copy > p', e => e.textContent);

return confirmationMessageText

};

Here is my index.js script where I try to import the constant confirmationMessageText and use it in a test:

const confMessage = require('./test/uiTests/customerChoices');
const expect = require('chai').expect;
const puppeteer = require('puppeteer');
const _ = require('lodash');
const chai = require('chai');

describe('Update customer choices', function() {

      it('test all customer choices', async function() {
        const url = _.get(url, `${env}`);
        await page.goto(url);

        await customerChoices(page);
        const cm = awaitCustomerChoices(page);
        expect(cm).to.equal('Thank you. Your choices have been updated.');
      expect(cm).to.equal('Thank you. Your choices have been updated.');
        console.log(confirmationMessageText);
      });

I'm unclear why confirmationMessageText is "Thank you. Your choices have been updated.' from the Puppeteer script but 'undefined' from within index.js?

In case it's useful, my package.json looks like:

"engines": {
  "node": ">=6"
},
"dependencies": {
  "chai": "^4.1.2",
  "lodash": "^4.17.10",
  "mocha": "^5.2.0",
  "moment": "^2.22.2",
  "newman": "^4.0.1",
  "puppeteer": "^1.6.2",
  "yargs": "^12.0.1",
  "express": "^4.16.4",
  "supertest": "^3.3.0"
},
"devDependencies": {
  "chai-as-promised": "^7.1.1",
  "express": "^4.16.4",
  "supertest": "^3.3.0"
}
}

Upvotes: 0

Views: 493

Answers (1)

Estus Flask
Estus Flask

Reputation: 222548

module.exports shouldn't be changed asynchronously, especially if it's supposed to be changed on function call. CommonJS modules are evaluated once, confMessage is async(page) => {...} function.

The function should just return the result:

module.exports = async(page) => {
  ...
  return confirmationMessageText;
};

And used like:

const cm = await customerChoices(page);

Upvotes: 1

Related Questions