CasperJS 包含一些非常有用的工具用来对 Web 网站进行功能性的测试,例如我们可以编写如下的 JavaScript 脚本来测试 Google 的搜索:
01 | var casper = require( 'casper' ).create(); |
03 | casper.start( 'http://www.google.fr/' , function () { |
04 | this .test.assertTitle( 'Google' , 'google homepage title is the one expected' ); |
05 | this .test.assertExists( 'form[action="/search"]' , 'main form is found' ); |
06 | this .fill( 'form[action="/search"]' , { |
11 | casper.then( function () { |
12 | this .test.assertTitle( 'foo - Recherche Google' , 'google title is ok' ); |
13 | this .test.assertUrlMatch(/q=foo/, 'search term has been submitted' ); |
14 | this .test.assertEval( function () { |
15 | return __utils__.findAll( 'h3.r' ).length >= 10; |
16 | }, 'google search for "foo" retrieves 10 or more results' ); |
19 | casper.run( function () { |
20 | this .test.renderResults( true ); |
如你所见,casper.test
是 tester.Tester 对象实例的引用,用来对结果进行断言和输出。
tester.Tester
API documentation 请看 dedicated section.
现在开始运行这个测试脚本:
1 | $ casperjs samples/googletest.js |
下面是运行结果:
如果是断言失败,那可能就是下面这种结果:
将结果导出为 xUnit 格式
CasperJS 可以将测试结果导出为 xUnit 的 XML 格式,这样就可以方便的与一些持续集成工具如Jenkins 集成. 可以使用如下代码来保存:
2 | this .test.renderResults( true , 0, 'log.xml' ); |
还有一个更酷的方法就是通过 CLI 参数解析来增加选项:
2 | this .test.renderResults( true , 0, this .cli.get( 'save' ) || false ); |
然后:
1 | $ casperjs test .js --save=log.xml |
CasperJS tests
CasperJS 有它自己的单元测试和功能测试套件,在 tests 子目录中,要运行这个测试套件可以执行如下命令:
2 | $ casperjs test tests/suites |
组织你的测试
将所有的测试写在一个文件里是一件很不爽的时间,你可以将这些测试用例分开独立存放。
但很重要的两点是:
-
不要 在独立的测试文件里创建新的 Casper 实例
-
测试结束后要调用 Tester.done()
方法
下面是第一个简单的测试文件:
3 | casper.test.comment( 'My first test file' ); |
4 | casper.test.assert( true , "true is so true" ); |
再来一个:
03 | casper.test.comment( 'This is my second test file, a bit more async' ); |
05 | casper.start( 'http://my.location.tld/' , function () { |
06 | this .test.assertNot( false , "false is so false" ); |
09 | casper.run( function () { |
标准的 Casper 累实例存储在一个名为 casper 变量中,你无需重复定义直接使用即可。
casperjs test
命令用来执行某个目录下的所有测试文件:
1 | $ casperjs test /path/to/ test / dir / |
理论上你将看到如下输出:
当然,你也可以执行某个单独的测试文件:
1 | $ casperjs test /path/to/ test / dir /test1.js |
casper test 命令还包含其他一些参数:
--xunit=<filename>
用来导出测试结果到 xUnit XML 文件格式--direct
直接输出日志信息到控制台--log-level=<logLevel>
设置日志级别 (请看 related section)
扩展 Casper
$ casper test [path]
命令其实只是$ casper /path/to/casperjs/tests/run.js [path]
命令的更快捷的执行方式,因此,如果你需要对这个过程进行扩展,最好的方法是直接修改 run.js 这个文件。