gpt4 book ai didi

javascript - 组件服务没有被注入(inject) Jasmine 测试

转载 作者:行者123 更新时间:2023-11-29 21:07:58 28 4
gpt4 key购买 nike

给出以下测试。
$provided 服务未被注入(inject)。如果我在 karma 中调试测试,我可以看到所提供的服务是真实的,而不是模拟的

真正奇怪的是,如果我删除 $provide.service... 我会得到一个错误 Error: [$injector:unpr] Unknown provider: ficaServiceProvider <- ficaService.这显然意味着服务正在注册,只是没有被替换?

describe("component: FicaStatusComponent",
function () {
var fs;
beforeEach(function () {
module("aureus",
function ($provide) {
$provide.service("ficaService", function () {
this.status = function () {
return $q(function (resolve, reject) {
resolve([{ documentType: { id: 1 } }]);
});
}
})
});

});

beforeEach(inject(function (_$componentController_, _ficaService_) {
$componentController = _$componentController_;
fs = _ficaService_;
}));

it("should expose a `fica` object", function () {
console.log('should expose');
var bindings = {};
var ctrl = $componentController("ficaStatus", null, bindings);
expect(ctrl.fica).toBeDefined();
});

it("compliant with no documents should not be compliant",
function () {
var ctrl = $componentController("ficaStatus");
expect(ctrl.fica.length).toEqual(1);
});
}
);

第二个测试不符合任何文件...失败。

Chrome 56.0.2924 (Windows 10 0.0.0) component: FicaStatusComponent compliant with no documents should not be compliant FAILED Error: Unexpected request: GET api/fica/status/

我也试过这个,期望注入(inject)一个空对象,但是“真正的”服务仍然存在吗?

        module("aureus", function($provide) {
$provide.value("ficaService", function() { return {}; });
$provide.service("ficaService", function() { return {}; });
});

下面是组件 Controller 的实现:

var FicaStatusController = (function () {
function FicaStatusController($log, $loc, ficaService) {
var _this = this;
this.$log = $log;
this.$loc = $loc;
this.ficaService = ficaService;
this.fica = [];
this.ficaService.status(1234).then(function (_) { return _this.fica = _; });
}

FicaStatusController.$inject = ["$log", "$location", "IFicaStatusService"];
module("aureus").component("ficaStatus", new FicaStatusComponent());
module("aureus").service("IFicaStatusService", FicaStatusService);

服务如下:

var FicaStatusService = (function () {
function FicaStatusService($log, $http) {
this.$log = $log;
this.$http = $http;
}
FicaStatusService.prototype.status = function (accountNumber) {
var url = "api/fica/status/" + accountNumber;
this.$log.log("status: " + url);
return this.$http
.get(url)
.then(function (_) { return _.data; });
};
return FicaStatusService;
}());

...

最佳答案

你已经像这样在你的模块中添加了你的服务:

module("aureus").service("IFicaStatusService", FicaStatusService);

这意味着您需要使用 $provide 提供 IFicaStatusService 而不是 ficaService

关于javascript - 组件服务没有被注入(inject) Jasmine 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048754/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com