微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在相对路径中使用require

如何解决在相对路径中使用require

我遇到了同样的问题,最终得到了以下解决方案。在我的 量角器 配置文件中,我有一个变量,用于存储我的e2e测试的基本文件夹的路径。此外, 量角器 配置还提供了onPrepare回调,您可以在其中使用称为的global变量来为测试创建全局变量。您将它们定义为该global变量的属性,并使用与全局变量browserelement测试相同的方式。我用它来创建自定义的全局require函数来加载不同类型的实体:

// __dirname retuns a path of this particular config file
// assuming that protractor.conf.js is in the root of the project
var basePath = __dirname + '/test/e2e/';
// /path/to/project/test/e2e/

exports.config = {

    onPrepare: function () {

        // "relativePath" - path, relative to "basePath" variable

        // If your entity files have suffixes - you can also keep them here
        // not to mention them in test files every time

        global.requirePO = function (relativePath) {
            return require(basePath + 'po/' + relativePath + '.po.js');
        };

        global.requireHelper = function (relativePath) {
            return require(basePath + 'helpers/' + relativePath + '.js');
        };

    }

};

然后,您可以立即在测试文件中使用这些全局实用程序方法

"use strict";

var localStorageHelper = requireHelper('localStorage');
// /path/to/project/test/e2e/helpers/localStorage.js

var loginPage = requirePO('login');
// /path/to/project/test/e2e/po/login.po.js

var productShowPage = requirePO('product/show');
// /path/to/project/test/e2e/po/product/show.po.js


describe("Login functionality", function () {

    beforeEach(function () {
        browser.get("/#login");

        localStorageHelper.clear();
    });

    // ...

});

解决方法

我们在量角器上进行了大量的端到端测试。我们正在遵循Page
Object模式,这有助于我们保持测试的清洁和模块化。我们还有一组帮助程序功能,可以帮助我们遵循DRY原理

问题:

单个规范可能需要多个页面对象和帮助程序模块。例如:

"use strict";

var helpers = require("./../../helpers/helpers.js");
var localStoragePage = require("./../../helpers/localStorage.js");
var sessionStoragePage = require("./../../helpers/sessionStorage.js");

var loginPage = require("./../../po/login.po.js");
var headerPage = require("./../../po/header.po.js");
var queuePage = require("./../../po/queue.po.js");

describe("Login functionality",function () {

    beforeEach(function () {
        browser.get("/#login");

        localStoragePage.clear();
    });

    // ...

});

你可以看到,我们有一个目录遍历在每一个需要声明:./../..。这是因为我们有一个specs目录,其中将规范和多个目录存放在受测试的应用程序功能分组下。

问题:

解决量角器中相对路径问题的规范方法是什么?

换句话说,我们要避免遍历树,而要导入模块。而是从基本应用程序目录中查找下来会更加干净。


尝试和想法:

关于此问题,有一篇很棒的文章:Node.js的更好的本地require()路径,但是我不确定在使用Protractor开发测试时建议使用哪个选项。

我们也尝试过使用require.main来构造路径,但是它指向node_modules/protractor目录而不是我们的应用程序目录。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。