在两个Javascript文件之间共享常量值

时间:2018-12-07 14:52:42

标签: javascript node.js mocha async.js

一般来说,我是JS和Node的新手。我正在尝试使用Puppeteer来简单地获取

标记的文本值并将其保存为常量。然后,我尝试在Mocha测试所在的“基类”(index.js)中使用该值。由于某种原因,我很挣扎。我正在使用异步。

我的文件结构是:

enter image description here

这是我的木偶剧本:

//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

};

这是我的index.js脚本,在这里我尝试导入常量ConfirmationMessageText并在测试中使用它:

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

我不清楚为什么ConfirmationMessageText是“谢谢。您的选择已更新。”是来自Puppeteer脚本,还是来自index.js内部的“未定义”?

如果有用,我的package.json如下:

"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"
}
}

1 个答案:

答案 0 :(得分:1)

module.exports不应异步更改,尤其是应该在函数调用时更改的情况下。 CommonJS模块只计算一次,confMessageasync(page) => {...}函数。

该函数应只返回结果:

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

并按如下方式使用:

const cm = await customerChoices(page);