2014-12-26 28 views
2

我是node.js的新手,从事异步框架工作已经有一段时间了。 在程序语言如Python中这样很容易通过他们拥有的输入列表和预期产出,然后循环测试:如何在nodejs中重复使用异步调用的测试函数?

tests = { 
    1: [2, 3], 
    2: [3, 4], 
    7: [8, 9], 
} 

for input, expected_out in tests.items(): 
    out = myfunc(input) 
    assert(out == expected_out) 

我试图做的NodeJS /摩卡/应类似:

var should = require('should'); 

function myfunc(x, cb) { var y = x + 1; var z = x + 2; cb([y, z]); }; 

describe('.mymethod()', function() { 
    this.timeout(10000); 
    it('should return the correct output given input', function(done) { 
     var testCases = { 
       1: [2, 3], 
       2: [3, 4], 
       7: [8, 9], 
      }; 

     for (input in testCases) { 
      myfunc(input, function (out) { 
       var ev = testCases[input]; 
       out.should.equal(ev); 
      }); 
     } 
    }) 
}) 

这导致:

AssertionError: expected [ '11', '12' ] to be [ 2, 3 ] 
    + expected - actual 

    [ 
    + 2 
    + 3 
    - "11" 
    - "12" 
    ] 

我不知道在哪里[ '11', '12']从何而来,但也有点线程安全问题。

任何人都可以向我解释这些意外的价值来自哪里?

+1

对于你的情况(比较数组)使用.eql而不是.equal(它只是===里面)。但是.eql做了深入的比较。 –

回答

3

看来您正在传递给myfuncinput正被视为String。看看这个答案。

Keys in Javascript objects can only be strings?

试试这个,

var should = require('should'); 

function myfunc(x, cb) { var y = x + 1; var z = x + 2; cb([y, z]); }; 

describe('.mymethod()', function() { 
    this.timeout(10000); 
    it('should return the correct output given input', function(done) { 
     var testCases = { 
      1: [2, 3], 
      2: [3, 4], 
      7: [8, 9], 
     }; 

     for (input in testCases) { 
      input = parseInt(input) 
      myfunc(input, function (out) { 
       var ev = testCases[input]; 
       out.should.equal(ev); 
      }); 
     } 
    }) 
}) 

在这里,我已经解析了input它的整数值。