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

时间:2015-06-10 19:14:44

标签: javascript jasmine

我开始修改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);
    };
};

1 个答案:

答案 0 :(得分:0)

首先,从您发布的代码看起来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);
    });
});

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

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

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

{{1}}