0

尝试执行 jasmine-node 测试时出现以下错误。

我正在尝试测试以下 javascript

var StringDecoder = require('string_decoder').StringDecoder;
var decoder = new StringDecoder('utf8');

Nndb = function(child_process) {
    this.child_process = child_process;
};

Nndb.prototype.invokePhantomProcess = function( phantomScriptToRun, offSet) {

    var child =  this.child_process.spawn('phantomjs', [phantomScriptToRun, offSet]);
    child.stdout.on('data',function(data){

        console.log(decoder.write(data));

    });

    child.stderr.on('data', function (data) {
        console.log('stderr: ' + data);
    });

    child.on('exit', function (code) {
        console.log('child process exited with code ' + code);
    });

    return 0;

};

exports.Nndb = Nndb;

具有以下测试规范:

require('../src/TDDQuestion.js');

describe("Verify", function() {

    it("spawns child process", function() {

        var stdout = {
            on: function() {}
        };

        var child_process = {
            stdout: stdout,
            spawn: function(){return this;}
        };

        spyOn(child_process,"spawn").andReturn(child_process);
        spyOn(child_process, "stdout").andReturn(stdout);

        var nndb = new Nndb(child_process);

        nndb.invokePhantomProcess('../src/TDDQuestion.js', 0);
        expect(child_process.spawn).toHaveBeenCalledWith( 'phantomjs',['../src/TDDQuestion.js',0]);

    });


});

并得到错误:

enter Stacktrace:
 TypeError: Object function () {
spyObj.wasCalled = true;
spyObj.callCount++;
var args = jasmine.util.argsToArray(arguments);
spyObj.mostRecentCall.object = this;
spyObj.mostRecentCall.args = args;
spyObj.argsForCall.push(args);
spyObj.calls.push({object: this, args: args});
return spyObj.plan.apply(this, arguments);
} has no method 'on'
    at Nndb.invokePhantomProcess

(/Users/.../src/TDDQuestion.js:11:18)
at null.<anonymous> (/Users/.../spec/TDDQuestionSpec.js:21:14)

我看到测试规范中的对象标准输出中存在方法“on”。

我还观察到,当更改 TDDQuestion.js 中的行时

child.stdout.on //returns a function causing the error

child.stdout().on //returns the stdout object with the 'on' method

解决了这个问题。

4

1 回答 1

0

删除对标准输出的监视并将其视为属性(它是)解决了这个问题。间谍活动仅适用于作为方法上的函数的属性。

我在此处粘贴更正后的 TDDSpecQuestion.js。

require('../src/TDDQuestion.js');

describe("Verify", function() {

    it("spawns child process", function() {


        var stdout = {
            on: function() {}
        };
        var stderr = {
            on: function() {}
        }

        var child_process = {
            stderr: stderr,
            stdout: stdout,
            spawn: function(){return this;},
            on: function(){}
        };
        debugger;
        spyOn(child_process,"spawn").andReturn(child_process);
        var nndb = new Nndb(child_process);

        nndb.invokePhantomProcess('../src/TDDQuestion.js', 0);
        expect(child_process.spawn).toHaveBeenCalledWith( 'phantomjs',['../src/TDDQuestion.js',0]);

    });


});
于 2013-12-15T16:27:30.633 回答