0

我是 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;
});

这是我的测试规范,它在期望语句上失败(错误:预期的间谍 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();

    }));
});
4

1 回答 1

1

请添加此更改。

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

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

于 2016-02-10T15:16:13.937 回答