6

几天前刚开始使用 CasperJS。

我今天创建了一个脚本来测试 LocalStorage 的行为方式以及是否可以禁用它,因为这是防止测试相互影响所必需的。

背景

我正在开发一个要求在第一页上输入值的 Backbone 向导。当您单击 Continue 按钮时,它会将值保存到 LocalStorage,然后将其显示在第二页上。

我正在使用casperjs test <script.js>有和没有--local-storage-quota=0

第一次尝试

编写了一个 CasperJS 脚本,它执行以下操作:

  1. 加载页面
  2. 检查模型的内容(应该是空的)
  3. 点击继续
  4. 在第 2 页加载后检查模型的内容(包含值,因为它应该)
  5. 使用 casper.thenOpen() 直接打开第 2 页作为新页面
  6. 在第 2 页加载后检查模型的内容

如果启用了 LocalStorage,则第 6 步的结果应该与第 4 步相同(模型中存在值)。

如果 LocalStorage 被禁用,第 6 步的结果应该与第 2 步相同(模型为空)。

每次我运行脚本时,我都会确定 LocalStorage 已启用。'--local-storage-quota=0' 参数没有任何区别。

第二次尝试

那时,我决定确定 LocalStorage 是否附加到特定的 Casper 实例。如果是这样,那么我可以通过为每个测试创建一个新的 Casper 实例来解决这个问题,从而从一个干净的状态开始。

var Casper = require( 'casper' );

casper = Casper.create();
casper.test.begin( 'test for Local Storage, part 1', 0, function suite (test) { ... });

casper = Casper.create();
casper.test.begin( 'test for Local Storage, part 2', 0, function suite (test) { ... });

但是,第二个测试套件永远不会运行。我不知道 Casper 是否不打算在同一个脚本中创建多个实例,或者我只是不正确地组织它。

附录

我应该补充一点,所有测试套件都以以下步骤结束,以防相关:

casper.run( function () {
    test.done();
    casper.exit();
});

文档仅指定 test.done() 是必需的。但是,我的测试脚本将永远挂起,直到我添加对 casper.exit() 的调用。

4

1 回答 1

1

您不能在 phantomjs 中禁用 localStorage 或 sessionStorage。但是,建议每次运行测试时清理执行环境。我建议添加具有完整设置的通用测试功能,如下所示:

function beginTest(casper, description, num, tests){
    function clearStorage(){
        casper.evaluate(function() {
            localStorage.clear();
            sessionStorage.clear();
        });
    }
    // Select between two possible signatures and queue a casper test
    if (typeof num == "number" && typeof tests == "function") {
        casper.test.begin(description, num, function suite(test){
            phantom.clearCookies();
            casper.start(config.baseurl, clearStorage);
            tests(test);
            casper.run(function(){
                test.done();
            });
        });
    } else if (typeof num == "function" && !tests) {
        casper.test.begin(description, function suite(test){
            phantom.clearCookies();
            casper.start(config.baseurl, clearStorage);
            num(test);
            casper.run(function(){
                test.done();
            });
        });
    }
}

然后你可以调用它

beginTest(casper, 'test for Local Storage, part 1', 0, function suite(test){ /* ... */ });
beginTest(casper, 'test for Local Storage, part 2', 0, function suite(test){ /* ... */ 
于 2014-06-09T17:12:52.637 回答