Phantomjs 如何将Sinon与CasperJS一起使用?

Phantomjs 如何将Sinon与CasperJS一起使用?,phantomjs,require,casperjs,sinon,Phantomjs,Require,Casperjs,Sinon,如何将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}']); c

如何将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是在全球和本地安装的,并且在节点交互模式下,该确切的require行工作良好


有人能给我发个帖子或给我指一个例子,说明Sinon与CasperJS一起使用吗?它不需要专门进行ajax模拟。任何用法都可以。

嗯,这里有多个问题。首先,您试图像在node中一样要求
sinon
,但它在casper中不起作用,因为casper不关心您是否有node\u modules目录,它也不查看它。我假设您已在node_模块目录中安装了sinon,因此您应该执行以下操作:

var sinon = require('./node_modules/sinon');
诀窍在于,您只能使用相对路径来获取安装在节点模块中的模块,因为对于casper来说,没有解析节点模块目录这样的事情

下一部分您做错了,似乎您混淆了phantomjs端和客户端。上面的脚本在phantomjs端进行计算,html中包含的脚本在客户端进行计算。这两个,彼此不共享任何内存,全局对象是不同的。所以您不能执行
sinon.fakeServer.create()在phantomjs端,因为它试图创建一个假的
XMLHttpRequest
,但它在phantomjs端不存在,它存在于客户端。所以技术上你不需要在这里运行它

因此,您需要做的是评估客户端中的sinon模块,并评估客户端中的脚本

这就引出了以下代码:

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')的调用,因为我们在客户端评估sinon时不再需要它了