AngularJS和Jasmine测试工厂

时间:2016-02-10 14:38:33

标签: angularjs unit-testing jasmine spyon

我是angularjs单元测试的新手。我有一个工厂,我试图用茉莉花来监视,我无法弄清楚测试规范的语法。以下是工厂:

app.factory('assetFactory', function ($http) {
    var baseAddress = "../api/";
    var url = "";
    var factory = {};

    factory.getAssets = function (term) {
        url = baseAddress + "asset/search/" + term;
        return $http.get(url);
    };
    return factory;
});

这是我的测试规范,它在expect语句中失败(错误:已调用预期的spy getAssets):

describe('assetFactory', function () {
    beforeEach(function () {
        module('fixedAssetApp');
    });

    beforeEach(inject(function (assetFactory) {
        spyOn(assetFactory, 'getAssets').and.callThrough();
    }));

    it('should be defined', inject(function (assetFactory) {
        expect(assetFactory).toBeDefined();
    }));

    it('should have been called, inject(function (assetFactory) {
        expect(assetFactory.getAssets).toHaveBeenCalled();

    }));
});

1 个答案:

答案 0 :(得分:1)

请添加此更改。

beforeEach(inject(function (assetFactory) {
        spyOn(assetFactory, 'getAssets').and.callThrough();
        assetFactory.getAssets();
    }));

为了toHaveBeenCalled()返回true,您必须在beforeEachit块中调用您的函数。