在JasmineJS中添加实用程序名称空间



我开始修改JasmineJS测试套件,有一些日志调用我想要清理。具体来说,我想在测试规范的目录中添加一个utilities.js文件…并在我所有的测试规范中引用它。

现在有两个测试规格testSuite1.spec.jstestSuite2.spec.js,一个page.js有一堆例程。

这似乎不起作用。知道为什么吗?

testSuite1.spec.js

var page = require('./page.js');
var testUtilities = require('./testUtilities.js');
var params = browser.params;
describe("App dashboard", function () {
browser.ignoreSynchronization = true;
var params = browser.params;
describe("login", function () {
    it("should go to login page", function () {
        testUtilities.writeTitleToLog('Login');
        testUtilities.writeToLog("resizing window and going to home page");

testUtilities.js

var testUtilities = function () {
    "use strict";
    this.writeToLog = function (message, isTitleMessage) {
        if (typeof message !== 'string') {
            console.log(Date() + " TestSpec -- WARNING: messaged was not a string");
        }
        if (isTitleMessage) {
            console.log("n" + Date() + " TestSpec - " + message.toUpperCase() + 'n');
        } else {
            console.log(Date() + " TestSpec —- " + message);
        }
    };
    this.writeTitleToLog = function (message) {
        this.writeToLog(message, true);
    };
};

首先,从你发布的代码来看,testUtilities.js似乎没有导出任何东西。否则,你的规格中的testUtilities将是undefined。要解决这个问题,您需要显式地声明导出:

exports.testUtilities = function () {
    "use strict";
     //...
};

第二件应该修复的事情:在你的testUtilities中,你声明了一个严格模式的函数,其中一些实用程序方法被添加到this中,但这只会在你用new关键字(如构造函数)调用它时才会起作用:

var testUtilities = new (require('./testUtilities.js'))();

可能不是那么优雅。此外,它需要始终将正确的this传递给writeTitleToLog(),因为它使用this来查找writeToLog()

为了解决这个问题,可以重写testUtilities.js以导出一些实用函数:

"use strict";
function writeToLog(message, isTitleMessage) {
    if (typeof message !== 'string') {
        console.log(Date() + " TestSpec -- WARNING: messaged was not a string");
    }
    if (isTitleMessage) {
        console.log("n" + Date() + " TestSpec - " + message.toUpperCase() + 'n');
    } else {
        console.log(Date() + " TestSpec —- " + message);
    }
}
function writeTitleToLog(message) {
    writeToLog(message, true);
}
module.exports = {
    writeToLog: writeToLog,
    writeTitleToLog: writeTitleToLog
};

然后它的用法与你的问题完全相同:

var testUtilities = require('./testUtilities.js');
describe("something", function () {
    testUtilities.writeTitleToLog("Something is being tested");
    it("should be ok to call test utilities", function () {
        testUtilities.writeToLog("Executing sanity check");
        expect(true).not.toBe(false);
    });
});

或者如果你已经在你的项目中使用ES2015语法,它可以简化(在我看来)解构赋值的语法糖:

const {writeToLog, writeTitleToLog} = require('./testUtilities.js');
describe("something", function () {
    writeTitleToLog("Something is being tested");
    it("should be ok to call test utilities", function () {
        writeToLog("Executing sanity check");
        expect(true).not.toBe(false);
    });
});

相关内容

  • 没有找到相关文章

最新更新