我有一个使用fileReader服务的解析器服务:
app.factory( 'parserService', [ '$q', 'fileReader', function ( $q, fileReader ) {
var parser = {};
parser.addASTtoFilesInTree = function ( fileTree ) {
var promises = [];
traverse(fileTree);
return $q.all(promises);
}
return parser;
}]);
和FileReader是:
app.factory( 'fileReader', [ '$q', function ($q) {
var fileReader = {};
fileReader.readFile = function( file ) {
var defer = $q.defer();
var reader = new FileReader();
reader.onload = function(e) {
defer.resolve(e.target.result);
};
reader.onerror = function(msg){
console.log(msg);
//add defer on error
};
reader.readAsBinaryString(file.ref);
return defer.promise;
};
return fileReader;
}]);
我目前正在尝试使用karma - jasmine创建一个测试来测试parseService中的addASTtoFilesInTree函数。
describe( "parser tests" , function() {
var parserService, $rootScope;
var mockFileReader = {
readFile: function( file ) {
var defer = $q.defer();
defer.resolve(file.ref.content);
console.log("in mockFileReader"); // this never gets called
return defer.promise;
}
};
var mockFileContent = "..."
var mockAST = { ... }
var itemOne = {...};
var parsedItemOne = { ... }
var mockFileTree = { ... };
beforeEach( function() {
//load the module
module('FYP');
//using mock service
module( function($provide) {
$provide.value = ('fileReader', mockFileReader);
});
//inject service for testing
inject( function( _$rootScope_, _parserService_) {
$rootScope = _$rootScope_;
parserService = _parserService_;
});
});
describe( "addASTtoFilesInTree", function() {
it('should add AST to all JS file', function() {
parserService.addASTtoFilesInTree(mockFileTree).then(function() {
console.log("in THEN"); //this never gets called
});
$rootScope.$digest();
expect(mockFileTree['root'].files['itemOne']).toEqual(parsedItemOne);//fails since it compares the two objects before promise is returned
});
});
});
测试失败,因为它在promise返回之前比较了两个对象。我错过了什么吗?
答案 0 :(得分:3)
//load the module
module('FYP');
//using mock service
module( function($provide) {
$provide.decorator('fileReader', function() {
return mockFileReader;
});
});
//inject service for testing
inject( function( _$rootScope_, _parserService_, _$q_ ) {
$rootScope = _$rootScope_;
parserService = _parserService_;
$q = _$q_;
});
beforeEach(module('FYP'));
beforeEach(function () {
module( function($provide) {
$provide.value('fileReader', mockFileReader);
});
});
beforeEach(inject( function( _$rootScope_, _parserService_, _$q_) {
$rootScope = _$rootScope_;
parserService = _parserService_;
$q = _$q_;
}));