gpt4 book ai didi

unit-testing - 测试 Yeoman 生成的 Angular 工厂/服务

转载 作者:行者123 更新时间:2023-12-04 02:37:46 25 4
gpt4 key购买 nike

我用 yeoman 创建了一个应用

yo angular --minsafe

我想测试我创建的工厂/服务

yo angular:factory analyticsService

产生/app/scripts/services/analyticsService.js

'use strict';

angular.module('angularPlaygroundApp')
.factory('analyticsService', function ($resource) {
// Service logic
// ...

var meaningOfLife = 42;

// Public API here
return {
someMethod: function () {
return meaningOfLife;
}
};
});

和测试/test/spec/services/analyticsService.js

'use strict';

describe('Service: Analyticsservice', function () {

// load the service's module
beforeEach(module('angularPlaygroundApp'));

// instantiate service
var Analyticsservice;
beforeEach(inject(function (_Analyticsservice_) {
Analyticsservice = _Analyticsservice_;
}));

it('should do something', function () {
expect(!!Analyticsservice).toBe(true);
});

});

running grunt test produces the following failed test for the service

Running "karma:unit" (karma) task INFO [karma]: Karma v0.10.8 server started at http://localhost:8080/ INFO [launcher]: Starting browser Chrome WARN [watcher]: Pattern "/Users/lsims/projects/angular-playground/test/mock/*/.js" does not match any file. INFO [Chrome 31.0.1650 (Mac OS X 10.9.0)]: Connected on socket MTgYIXPHDT3JCSNU0ww9 Chrome 31.0.1650 (Mac OS X 10.9.0) Service: Analyticsservice should do something FAILED Error: [$injector:unpr] Unknown provider: AnalyticsserviceProvider <- Analyticsservice

我的问题是如何在 Angular 中测试工厂/服务,更具体地说,如何测试 Yeoman 生成的服务和/或工厂?

提前致谢

最佳答案

它们的测试与您描述的几乎完全一样。但是,JavaScript 是区分大小写的,您已经更改了注入(inject)器要搜索的内容的大小写。

analyticsService != Analyticsservice

_Analyticsservice_ 语法允许您将服务的文字值用下划线括起来,这样您就可以将局部变量命名为相同的东西。因此,向 inject 请求 _Analyticsservice_ 是在请求​​以字符串 "Analyticsservice" 命名的服务。当您定义了名为 "analyticsService" 的服务时。

所以,我想你想要:

'use strict';

describe('Service: analyticsService', function () {

// load the service's module
beforeEach(module('angularPlaygroundApp'));

// instantiate service
var analyticsService;
beforeEach(inject(function (_analyticsService_) {
analyticsService = _analyticsService_;
}));

it('should do something', function () {
expect(!!analyticsService).toBe(true);
});
angular 中的

injector 总是将名称 Provider 附加到 manages 中对象的末尾。该错误告诉您注入(inject)器找不到名称为 "AnalyticsserviceProvider" 的对象。

关于unit-testing - 测试 Yeoman 生成的 Angular 工厂/服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20531565/

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