当前位置: 首页 > 文档资料 > CasperJS 中文文档 >

tester 模块

优质
小牛编辑
120浏览
2023-12-01

tester模块

Casper附带一个测试器模块和一个Tester类,提供用于单元和功能测试的API。默认情况下,您可以通过任何Casper类实例的测试属性来访问此类的实例。

提示

学习如何使用Tester API并且看到它如何运作的最好方法可能是去看看CasperJS自己的测试套件。

tester原型

assert()

调用方法:assert(Boolean condition[, String message])

断言所提供的条件严格解决为布尔值ture。

casper.test.assert(true, "true's true");
casper.test.assert(!false, "truth is out");
提示

同样也去看看类似的assertNot()函数。

assertDoesntExist()

调用方法: assertDoesntExist(String selector[, String message])

断言在远程DOM环境中不存在与提供的选择器表达式匹配的元素:

casper.test.begin('assertDoesntExist() tests', 1, function(test) {
    casper.start().then(function() {
        this.setContent('<div class="heaven"></div>');
        test.assertDoesntExist('.taxes');
    }).run(function() {
        test.done();
    });
});
提示

同样也去看看类似的assertExists()函数。

assertEquals()

调用方法:assertEquals(mixed testValue, mixed expected[, String message])

断言两个值是严格等价的:

casper.test.begin('assertEquals() tests', 3, function(test) {
    test.assertEquals(1 + 1, 2);
    test.assertEquals([1, 2, 3], [1, 2, 3]);
    test.assertEquals({a: 1, b: 2}, {a: 1, b: 2});
    test.done();
});
提示

同样也去看看类似的assertNotEquals()函数。

assertEval()

调用方法:assertEval(Function fn[, String message, Mixed arguments])

断言远程DOM中的代码评估严格解决为布尔值ture:

casper.test.begin('assertEval() tests', 1, function(test) {
    casper.start().then(function() {
        this.setContent('<div class="heaven">beer</div>');
        test.assertEval(function() {
            return __utils__.findOne('.heaven').textContent === 'beer';
        });
    }).run(function() {
        test.done();
    });
});

assertEvalEquals()

调用方法: assertEvalEquals(Function fn, mixed expected[, String message, Mixed arguments])

断言远程DOM中的代码评估结果严格等于期望值:

casper.test.begin('assertEvalEquals() tests', 1, function(test) {
    casper.start().then(function() {
        this.setContent('<div class="heaven">beer</div>');
        test.assertEvalEquals(function() {
            return __utils__.findOne('.heaven').textContent;
        }, 'beer');
    }).run(function() {
        test.done();
    });
});

assertElementCount()

调用方法: assertElementCount(String selector, Number count[, String message])

断言选择器表达式匹配给定数量的元素:

casper.test.begin('assertElementCount() tests', 3, function(test) {
    casper.start().then(function() {
        this.page.content = '<ul><li>1</li><li>2</li><li>3</li></ul>';
        test.assertElementCount('ul', 1);
        test.assertElementCount('li', 3);
        test.assertElementCount('address', 0);
    }).run(function() {
        test.done();
    });
});

assertExists()

调用方法: assertExists(String selector[, String message])

断言在远程DOM环境中存在与提供的选择器表达式匹配的元素:

casper.test.begin('assertExists() tests', 1, function(test) {
    casper.start().then(function() {
        this.setContent('<div class="heaven">beer</div>');
        test.assertExists('.heaven');
    }).run(function() {
        test.done();
    });
});
提示

同时建议你看看这个类似的函数assertDoesntExist()。

assertFalsy()

调用方法: assertFalsy(Mixed subject[, String message])

版本1.0新增

断言某个对象为假值。

提示

同时建议你看看这个类似的函数assertTruthy()。

assertField()

调用方法: assertField(String|Object input, String expected[, String message, Object options])

通过name属性或选择器表达式选定表单域,并断言给定的表单域的值和提供的值相同:

casper.test.begin('assertField() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        this.fill('form[name="gs"]', { q: 'plop' }, false);
        test.assertField('q', 'plop');
    }).run(function() {
        test.done();
    });
});

// Path usage with type 'css'
casper.test.begin('assertField() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        this.fill('form[name="gs"]', { q: 'plop' }, false);
        test.assertField({type: 'css', path: '.q.foo'}, 'plop');
    }).run(function() {
        test.done();
    });
});

版本1.0新增

该方法也可以使用在selecttextarea等文本域中了。

版本1.1新增

options参数允许设置与ClientUtils#getFieldValue()一起使用的选项。

输入参数将检测是否传入一个type与xpath或css和与它一起指定的属性路径。

assertFieldName()

调用方法: assertFieldName(String inputName, String expected[, String message, Object options])

版本1.1-beta3新增

断言给定的表单域具有提供的值。

casper.test.begin('assertFieldName() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        this.fill('form[name="gs"]', { q: 'plop' }, false);
        test.assertFieldName('q', 'plop', 'did not plop', {formSelector: 'plopper'});
    }).run(function() {
        test.done();
    });
});

assertFieldCSS()

调用方法:assertFieldCSS(String cssSelector, String expected, String message)

版本1.1新增

断言给定的表单字段具有给定的CSS选择器提供的值

casper.test.begin('assertFieldCSS() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        this.fill('form[name="gs"]', { q: 'plop' }, false);
        test.assertFieldCSS('q', 'plop', 'did not plop', 'input.plop');
    }).run(function() {
        test.done();
    });
});

assertFieldXPath()

调用方法:assertFieldXPath(String xpathSelector, String expected, String message)

版本1.1新增

断言给定的表单域具有提供给XPath选择器的值:

casper.test.begin('assertFieldXPath() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        this.fill('form[name="gs"]', { q: 'plop' }, false);
        test.assertFieldXPath('q', 'plop', 'did not plop', '/html/body/form[0]/input[1]');
    }).run(function() {
        test.done();
    });
});

assertHttpStatus()

调用方法:assertHttpStatus(Number status[, String message])

断言当前的HTTP状态代码与作为参数传递的状态代码相同:

casper.test.begin('casperjs.org is up and running', 1, function(test) {
    casper.start('http://casperjs.org/', function() {
        test.assertHttpStatus(200);
    }).run(function() {
        test.done();
    });
});

assertMatch()

调用方法:assertMatch(mixed subject, RegExp pattern[, String message])

断言所提供的字符串与提供的JavaScript RegExp模式匹配:

casper.test.assertMatch('Chuck Norris', /^chuck/i, 'Chuck Norris\' first name is Chuck');
提示

建议你也去看看类似的assertUrlMatch()和assertTitleMatch()函数。

assertNot()

调用方法:assertNot(mixed subject[, String message])

断言传入的对象为一个假值(falsy)。

casper.test.assertNot(false, "Universe is still operational");

assertNotEquals()

调用方法:assertNotEquals(mixed testValue, mixed expected[, String message])

版本0.6.7新增

断言两个值非严格相等。

casper.test.assertNotEquals(true, "true");

assertNotVisible()

调用方法:assertNotVisible(String selector[, String message])

断言匹配提供的选择器表达式的元素不可见:

casper.test.begin('assertNotVisible() tests', 1, function(test) {
    casper.start().then(function() {
        this.setContent('<div class="foo" style="display:none>boo</div>');
        test.assertNotVisible('.foo');
    }).run(function() {
        test.done();
    });
});

assertRaises()

调用方法:assertRaises(Function fn, Array args[, String message])

断言用给定的参数调用提供的函数引发一个javascript错误:

casper.test.assertRaises(function(throwIt) {
    if (throwIt) {
        throw new Error('thrown');
    }
}, [true], 'Error has been raised.');

casper.test.assertRaises(function(throwIt) {
    if (throwIt) {
        throw new Error('thrown');
    }
}, [false], 'Error has been raised.'); // fails

assertSelectorDoesntHaveText()

调用方法:assertSelectorDoesntHaveText(String selector, String text[, String message])

断言给定的文本在所有与提供的选择器表达式匹配的元素中不存在:

casper.test.begin('assertSelectorDoesntHaveText() tests', 1, function(test) {
    casper.start('http://google.com/', function() {
        test.assertSelectorDoesntHaveText('title', 'Yahoo!');
    }).run(function() {
        test.done();
    });
});

assertResourceExists()

调用方法:assertResourceExists(Function testFx[, String message])

testFx函数针对所有加载的资源执行,当至少有一个资源匹配时测试通过:

casper.test.begin('assertResourceExists() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertResourceExists(function(resource) {
            return resource.url.match('logo3w.png');
        });
    }).run(function() {
        test.done();
    });
});

简写版:

casper.test.begin('assertResourceExists() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertResourceExists('logo3w.png');
    }).run(function() {
        test.done();
    });
});
提示

去看看这个类似的Casper.resourceExists()函数吧.

assertTextExists()

调用方法:assertTextExists(String expected[, String message])

断言body标签的文本中含有给定的字符串:

casper.test.begin('assertTextExists() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertTextExists('google', 'page body contains "google"');
    }).run(function() {
        test.done();
    });
});

assertTextDoesntExist()

调用方法:assertTextDoesntExist(String unexpected[, String message])

版本1.0新增 断言body标签的文本中不含有给定的字符串:

casper.test.begin('assertTextDoesntExist() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertTextDoesntExist('bing', 'page body does not contain "bing"');
    }).run(function() {
        test.done();
    });
});

assertTitle()

调用方法:assertTitle(String expected[, String message])

断言远程页面的标题等于预期的标题:

casper.test.begin('assertTitle() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertTitle('Google', 'google.fr has the correct title');
    }).run(function() {
        test.done();
    });
});

assertTitleMatch()

调用方法:assertTitleMatch(RegExp pattern[, String message])

断言远程页面的标题与提供的RegExp模式匹配:

casper.test.begin('assertTitleMatch() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertTitleMatch(/Google/, 'google.fr has a quite predictable title');
    }).run(function() {
        test.done();
    });
});

assertType()

调用方法:assertType(mixed input, String type[, String message])

断言提供的输入是给定的类型:

casper.test.begin('assertType() tests', 1, function suite(test) {
    test.assertType(42, "number", "Okay, 42 is a number");
    test.assertType([1, 2, 3], "array", "We can test for arrays too!");
    test.done();
});
注意

类型名称总是以小写字母表示。

assertInstanceOf()

调用方法:assertInstanceOf(mixed input, Function constructor[, String message])

版本1.1新增

断言所提供的输入属于给定构造函数的:

function Cow() {
    this.moo = function moo() {
        return 'moo!';
    };
}
casper.test.begin('assertInstanceOf() tests', 2, function suite(test) {
    var daisy = new Cow();
    test.assertInstanceOf(daisy, Cow, "Ok, daisy is a cow.");
    test.assertInstanceOf(["moo", "boo"], Array, "We can test for arrays too!");
    test.done();
});

assertUrlMatch()

调用方法:assertUrlMatch(Regexp pattern[, String message])

断言当前页面的url匹配提供的RegExp模式:

casper.test.begin('assertUrlMatch() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertUrlMatch(/^http:\/\//, 'google.fr is served in http://');
    }).run(function() {
        test.done();
    });
});

assertVisible()

调用方法:assertVisible(String selector[, String message])

断言至少有一个与提供的选择器表达式匹配的元素是可见的:

casper.test.begin('assertVisible() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertVisible('h1');
    }).run(function() {
        test.done();
    });
});

assertAllVisible()

调用方法:assertAllVisible(String selector[, String message])

断言所有匹配提供的选择器表达式的元素都是可见的:

casper.test.begin('assertAllVisible() tests', 1, function(test) {
    casper.start('http://www.google.fr/', function() {
        test.assertAllVisible('input[type="submit"]');
    }).run(function() {
        test.done();
    });
});

begin()

调用方法

  • begin(String description, Number planned, Function suite)
  • begin(String description, Function suite)
  • begin(String description, Number planned, Object config)
  • begin(String description, Object config)

版本1.1新增

开始一个<planned>测试套件,套件回调将获取当前的Tester实例作为其第一个参数:

function Cow() {
    this.mowed = false;
    this.moo = function moo() {
        this.mowed = true; // mootable state: don't do that
        return 'moo!';
    };
}

// unit style synchronous test case
casper.test.begin('Cow can moo', 2, function suite(test) {
    var cow = new Cow();
    test.assertEquals(cow.moo(), 'moo!');
    test.assert(cow.mowed);
    test.done();
});
提示

planned参数是特别有用的,以防给定的测试脚本突然中断,让你没有明显的方式知道它和一个错误的成功状态。

一个更异步的例子:

casper.test.begin('Casperjs.org is navigable', 2, function suite(test) {
    casper.start('http://casperjs.org/', function() {
        test.assertTitleMatches(/casperjs/i);
        this.clickLabel('Testing');
    });

    casper.then(function() {
        test.assertUrlMatches(/testing\.html$/);
    });

    casper.run(function() {
        test.done();
    });
});
重要提示

done()必须被调用才能终止套件。在进行异步测试时,这是特别重要的,所以确保在所有事情都被执行时调用它。

Tester#begin()也接受一个测试配置对象,所以你可以添加setUp()tearDown()方法:

// cow-test.js
casper.test.begin('Cow can moo', 2, {
    setUp: function(test) {
        this.cow = new Cow();
    },

    tearDown: function(test) {
        this.cow.destroy();
    },

    test: function(test) {
        test.assertEquals(this.cow.moo(), 'moo!');
        test.assert(this.cow.mowed);
        test.done();
    }
});

colorize()

调用方法:colorize(String message, String style)

呈现彩色输出。基本上是Casper.Colorizer#colorize()的代理方法。

comment()

调用方法:comment(String message)

将注释式格式的消息写入stdout:

casper.test.comment("Hi, I'm a comment");

done()

调用方法:done()

版本1.1改动:planned参数已被弃用

标记一个以begin()开头的测试套件作为处理过程:

casper.test.begin('my test suite', 2, function(test) {
    test.assert(true);
    test.assertNot(false);
    test.done();
});

异步写法:

casper.test.begin('Casperjs.org is navigable', 2, function suite(test) {
    casper.start('http://casperjs.org/', function() {
        test.assertTitleMatches(/casperjs/i);
        this.clickLabel('Testing');
    });

    casper.then(function() {
        test.assertUrlMatches(/testing\.html$/);
    });

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

error()

调用方法:error(String message)

向stdout写入错误式格式的消息:

casper.test.error("Hi, I'm an error");

fail()

调用方法:fail(String message [, Object option])

将失败的测试条目添加到堆栈:

casper.test.fail("Georges W. Bush");
casper.test.fail("Here goes a really long and expressive message", {name:'shortfacts'});

formatMessage()

调用方法:formatMessage(String message, String style)

格式化消息以突出显示其中的某些部分。只在tester内部使用。

getFailures()

调用方法:getFailures()

版本1.0新增

版本1.1后弃用

检索当前测试套件的失败:

casper.test.assertEquals(true, false);
require('utils').dump(casper.test.getFailures());
casper.test.done();

会返回给你这样的信息:

$ casperjs test test-getFailures.js
Test file: test-getFailures.js
FAIL Subject equals the expected value
#    type: assertEquals
#    subject: true
#    expected: false
{
    "length": 1,
    "cases": [
        {
            "success": false,
            "type": "assertEquals",
            "standard": "Subject equals the expected value",
            "file": "test-getFailures.js",
            "values": {
                "subject": true,
                "expected": false
            }
        }
    ]
}
FAIL 1 tests executed, 0 passed, 1 failed.

Details for the 1 failed test:

In c.js:0
   assertEquals: Subject equals the expected value
提示

在版本1.1中,你可以通过监听测试失败事件记录测试失败:

var failures = [];

casper.test.on("fail", function(failure) {
  failures.push(failure);
});

getPasses()

调用方法:getPasses()

版本1.0新增

版本1.1后弃用

检索当前测试套件中成功测试用例的报告:

casper.test.assertEquals(true, true);
require('utils').dump(casper.test.getPasses());
casper.test.done();

会返回给你这样的信息:

$ casperjs test test-getPasses.js
Test file: test-getPasses.js
PASS Subject equals the expected value
{
    "length": 1,
    "cases": [
        {
            "success": true,
            "type": "assertEquals",
            "standard": "Subject equals the expected value",
            "file": "test-getPasses.js",
            "values": {
                "subject": true,
                "expected": true
            }
        }
    ]
}
PASS 1 tests executed, 1 passed, 0 failed.
提示

在版本1.1中,您可以通过听取测试成功事件来记录测试成功:

var successes = [];

casper.test.on("success", function(success) {
  successes.push(success);
});

info()

调用方法:info(String message)

将信息样式格式的消息写入标准输出:

casper.test.info("Hi, I'm an informative message.");

pass()

调用方法:pass(String message)

将成功的测试条目添加到堆栈中:

casper.test.pass("Barrack Obama");

renderResults()

调用方法:renderResults(Boolean exit, Number status, String save)

渲染测试结果,将结果保存在一个XUnit格式的文件中,并可以选择退出phantomjs:

casper.test.renderResults(true, 0, 'test-results.xml');
提示

在使用casperjs测试命令(请参阅测试文档)时,不会调用此方法,它会自动为您执行。

setUp()

调用方法:setUp([Function fn])

定义一个在使用begin()定义的每个测试之前执行的函数:

casper.test.setUp(function() {
    casper.start().userAgent('Mosaic 0.1');
});

要执行异步操作,请使用done参数:

casper.test.setUp(function(done) {
    casper.start('http://foo').then(function() {
        // ...
    }).run(done);
});
警告

如果您不打算异步使用该方法,则不要指定done参数。

skip()

调用方法:skip(Number nb, String message)

跳过给定数量的计划测试:

casper.test.begin('Skip tests', 4, function(test) {
    test.assert(true, 'First test executed');
    test.assert(true, 'Second test executed');
    test.skip(2, 'Two tests skipped');
    test.done();
});

tearDown()

调用方法:tearDown([Function fn])

定义一个在使用begin()定义的每个测试之后执行的函数:

casper.test.tearDown(function() {
    casper.echo('See ya');
});

要执行异步操作,请使用done参数:

casper.test.tearDown(function(done) {
    casper.start('http://foo/goodbye').then(function() {
        // ...
    }).run(done);
});
警告

如果您不打算异步使用该方法,则不要指定done参数。