如何在CasperJS上使用Sinon?

Dou*_*uch 4 require phantomjs 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();
  });
});
Run Code Online (Sandbox Code Playgroud)

然后这个脚本被调用如下:

casperjs test integration.js
Run Code Online (Sandbox Code Playgroud)

这是版本信息:

CasperJS version 1.1.0-DEV
at /usr/local/Cellar/casperjs/1/libexec,
using phantomjs version 1.9.1
Run Code Online (Sandbox Code Playgroud)

下一步是填写登录模式并提交,执行ajax查询.我想模仿jQuery的$.ajax方法.问题是我得到这个错误:" CasperError:找不到模块sinon ".但是Sinon是在全局和本地安装的,并且确切地说要求行在节点交互模式下工作正常.

有人可以发布或指出我在与CasperJS一起使用Sinon的例子的方向吗?它没有特别要做ajax嘲笑.任何用法都没问题.

Far*_*hat 5

那里有很多问题.首先,您尝试要求sinon它在节点中的工作方式,但它在casper中不起作用,因为casper并不关心您是否有node_modules目录,并且它不会查看它.我假设你已经在node_modules目录中安装了sinon,所以你应该这样做:

var sinon = require('./node_modules/sinon');
Run Code Online (Sandbox Code Playgroud)

诀窍是你只能使用相对路径来获取node_modules中安装的模块,因为对于casper,没有解析node_modules目录的问题.

下一部分你做错了,似乎你在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();
  });
});
Run Code Online (Sandbox Code Playgroud)

请注意,我没有包含调用var sinon = require('./node_modules/sinon');,因为我们在客户端评估sinon时不再需要它.