在指令的单元测试中模拟服务的值

时间:2015-06-18 16:54:27

标签: angularjs unit-testing jasmine karma-runner

在我的指令实例化中,我调用了一个返回一些数据的方法:

data = myService.getData()

以后我正在做的代码 something = data[id]

在业力中我有一个错误,因为未定义data,因此未定义spyOn(myService, 'getData').and.returnValue(mockData);。{/ p>

我试图模仿对服务的调用,如:

data

但问题仍然存在。 如何在我的测试中模拟 # Injector beforeEach(inject(($injector) -> $compile = $injector.get('$compile') $rootScope = $injector.get('$rootScope') $scope = $rootScope.$new() $httpBackend = $injector.get('$httpBackend') myService = $injector.get('myService') element = angular.element('<my-directive id="0"></my-directive>') template = $compile(element)($scope) $scope.$digest() spyOn(myService, 'getData').and.returnValue(someMockData) ))

func getAssetPhoto(asset: PHAsset, w: Double, h: Double) -> UIImage {
    let manager = PHImageManager.defaultManager()
    var option = PHImageRequestOptions()
    var photo = UIImage()
    var cropSideLength = min(asset.pixelWidth, asset.pixelHeight);
    var square = CGRect(x: 0.0, y: 0.0, width: Double(cropSideLength), height: Double(cropSideLength));

    var cropRect = CGRectApplyAffineTransform(square, CGAffineTransformMakeScale(CGFloat(1.0 / Double(asset.pixelWidth)), CGFloat(1.0 / Double(asset.pixelHeight))));
    option.synchronous = true
    option.normalizedCropRect = cropRect //CGRect(x: 0.5, y: 0.5, width: w, height: h)
    option.resizeMode = .Exact


    manager.requestImageForAsset(asset, targetSize: CGSize(width: w, height: h), contentMode: .AspectFill, options: option, resultHandler: {(result, info)->Void in
        photo = result
    })
    return photo
}

1 个答案:

答案 0 :(得分:2)

因此,不要使用实际服务,而是创建一个茉莉花间谍。

var myService = jasmine.createSpyObj('myService', ['getData']);

beforeEach(inject(($injector, $provide) => {

     // injector.gets ... don't get 'myService'
     . . . 

     $provide.value('myService', myService);

}))

it('should return data from service', () => {

    myService.getData.andReturn(['your mocked data']);

    // rest of test

})