2013-07-19 41 views
4

我如何使用Sinon与CasperJS?这是基本的测试文件我使用:如何使用Sinon与CasperJS?

var url = 'http://localhost:3000/'; 

var sinon = require('sinon'); 
var server = sinon.fakeServer.create(); 

server.respondWith("GET", "/login", 
    [200, { "Content-Type": "application/json" },'{"id": 12}']); 

casper.test.begin('integration',1,function suite(test){ 
    casper.start(url,function start(){ 
    test.assertHttpStatus(200,'http status is 200'); 
    }); 

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

然后这个剧本被称为像这样:

casperjs test integration.js 

这里是版本信息:

CasperJS version 1.1.0-DEV 
at /usr/local/Cellar/casperjs/1/libexec, 
using phantomjs version 1.9.1 

下一个步骤将是填写登录模式并提交,执行ajax查询。我想嘲笑jQuery的$.ajax方法。问题是我得到这个错误:“CasperError:找不到组件sinon”。但是Sinon在全球和本地安装,并且确实需要线路在节点交互模式下正常工作。

有人可以张贴或指向我的一个例子,其中Sinon与CasperJS一起使用的方向?它并不特别需要做ajax嘲弄。任何用法都可以。

回答

5

那么这里有很多问题。首先,你试图要求sinon就像它在节点中的工作方式一样,但它不能在casper中工作,因为casper不关心你是否有node_modules目录,也不会关注它。我假设你已经在你的node_modules目录中安装兴农,所以你应该这样做:

var sinon = require('./node_modules/sinon'); 

的技巧是,你只能使用相对路径得到安装在node_modules模块,因为卡斯帕有没有这样的事情作为解析node_modules目录。

接下来的一部分你做错了,好像你在幻灯片方和客户端之间感到困惑。您在上面的脚本在phantomjs一侧进行评估,并且包含在html中的脚本在客户端进行评估。这两个,不要相互分享任何记忆,全局对象是不同的。所以,你不能这样做在phantomjs侧sinon.fakeServer.create();,因为它试图创建一个假XMLHttpRequest,但这并不在phantomjs上存在,它存在于客户端。所以在技术上你不需要在这里运行它。

所以,你需要做的是,评估客户端兴农模块,并评估你有没有在客户端脚本。

这给我们带来了下面的代码:

var url = 'http://localhost:3000/'; 

// Patch the require as described in 
// http://docs.casperjs.org/en/latest/writing_modules.html#writing-casperjs-modules 
var require = patchRequire(require); 
var casper = require('casper').create({ 
    clientScripts: [ 
    // The paths have to be relative to the directory that you run the 
    // script from, this might be tricky to get it right, so play with it 
    // and try different relative paths so you get it right 
    'node_modules/sinon/pkg/sinon.js', 
    'node_modules/sinon/pkg/sinon-server-1.7.3.js' 
    ] 
}); 

casper.test.begin('integration',1,function suite(test){ 
    casper.start(url,function start(){ 
    test.assertHttpStatus(200,'http status is 200'); 
    casper.evalute(function() { 
     var server = sinon.fakeServer.create() 
     server.respondWith("GET", "/login", 
     [200, { "Content-Type": "application/json" },'{"id": 12}']); 
    }); 
    }); 

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

请注意,我并没有包括调用var sinon = require('./node_modules/sinon');,因为并不需要它了,因为我们正在评估在客户端兴农。