-1
我想在單元測試中創建假錯誤。
這是我的考試科目。
TypeError:無法調用未定義的方法'throws'。在單元測試
./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));
}
});
}
./test/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){
test.error(function(callback){
callback(b.readFile('notfound.sure'));
});
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.assert.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 Invalid file extension
3) should return not found
1 passing (9ms)
3 failing
1) Test with static input should return Invalid file extension:
AssertionError: function(){
throw new Error ("File not found in my computer",null);
} must be an instance of Error
+ expected - actual
-[Function]
+{
+ "captureStackTrace": [Function]
+ "stackTraceLimit": Infinity
+}
at Context.<anonymous> (test/m1.js:39:9)
2) Test with static input should return Invalid file extension:
Error: the function [Function] was thrown, throw an Error :)
3) Test with static input should return not found:
Error: the function [Function] was thrown, throw an Error :)
我該如何找到解決方案?
技術術語讓我現在轉了好幾個小時。
任何幫助,將不勝感激。
問候
沙立
現在。錯誤是一樣的:錯誤:功能[功能]被拋出,拋出一個錯誤:) – Sarit
這是不一樣的,並不涉及你的問題 –
讓我解決我的錯字和我的最新進展。保持一會兒。 – Sarit