“TypeError:在单元测试中无法调用未定义的方法'throws'

时间:2015-06-26 06:45:12

标签: javascript node.js unit-testing mocha

我想在单元测试中创建假错误。这是我的考试科目:

./ arn.js

var fs = require('fs');
var filename = ['README.md', 'ioio.txt', 'yoyo.txt','passwd'];

 exports.readFile = function(entry,callback){

     var cntent = fs.readFile(entry, "utf8" ,function(err, data) {
              if (err) throw err;
              if (callback && typeof(callback) === "function") {
                callback(null,data.substring(0,5));
              }
     });
 }

./测试/ m1.js

var mock = require('mock')
var realB = require("../arn.js")
var test = require('unit.js');


var trigger1 = function(){
    throw new Error ("File not found in my computer",null);
}; 

var b = mock("../arn.js", {
    fs: {
        readFile: function (entry,encoding, callback) {

            if (entry === "cody.txt"){
                  var regEx = /txt$/;
                  if(regEx.test(entry)){
                    callback(null,'text2');
                  }
            }

            if (entry === "notfound.sure"){
               callback(trigger1);              
            }
        }  
    }
}, require);


describe('Test with static input', function(){

    it('should return text2', function(done){
        b.readFile('cody.txt', function(err,a){
            test.value(a).match('text2');
            done();
        });
    });

    it('should return Invalid file extension', function(done){
        b.readFile('notfound.sure', function(err, a){
            test.error.hasMessage('File not found in my computer');
            done();
        });
    });

    it('should return not found', function(done){
        test.asswert.throws(
            function(){
                b.readFile('notfound.sure');
            },
            function(err){
                if ( (err instanceof Error)){
                    return true;
                }
            },
            "Expected error"
        );
        done();
    });
});

输出:

Test with static input
    ✓ should return text2
    1) should return Invalid file extension
    2) should return not found


  1 passing (8ms)
  2 failing

  1) Test with static input should return Invalid file extension:
     Error: the function [Function] was thrown, throw an Error :)


  2) Test with static input should return not found:
     TypeError: Cannot call method 'throws' of undefined
      at Context.<anonymous> (test/m1.js:46:16)

我如何找到适合他们的解决方案?技术术语让我绕了几个小时。

1 个答案:

答案 0 :(得分:0)

将第test.asswert.throws行更改为test.assert.throws