0

我有一个foo.js看起来像这样的文件:

var exec = require('child_process').exec
...
function start(){
  ...
  exec('open -g http://localhost:<port>');  // opens a browser window
}
// EOF

我想测试当我调用该start()函数时,会打开一个浏览器窗口。理想情况下,我想使用 Sinon 来存根exec(这样我们在自动化测试期间实际上不会打开浏览器窗口),并断言它exec被调用了。我尝试了很多方法,但都没有奏效。例如在foo_test.js

var subject = require('../lib/foo');

describe('foo', function(){
  describe('start', function(){
    it('opens a browser page to the listening address', function(){
      var stub = sinon.stub(subject, 'exec', function(){
        console.log('stubbed exec called');
      });  // fails with "TypeError: Attempted to wrap undefined property exec as function"
    });
  });
});

我该怎么做呢?

4

1 回答 1

0

不确定这是否是您要查找的内容,但快速搜索返回:

https://github.com/arunoda/horaa

基本上,它允许您存根库。从例子:

你的代码

//stored in abc.js
exports.welcome = function() {
    var os = require('os');

    if(os.type() == 'linux') {
        return 'this is a linux box';
    } else {
        return 'meka nam linux nemei :)';
    }
};

测试代码(注意 OS 的模拟)

//stored in test.js
var horaa = require('horaa');
var lib = require('./abc'); // your code
var assert = require('assert');

//do the hijacking
var osHoraa = horaa('os');
osHoraa.hijack('type', function() {
    return 'linux';
});

assert.equal(lib.welcome(), 'this is a linux box');

//restore the method
osHoraa.restore('type');

希望有帮助。

于 2013-02-20T20:14:51.873 回答