gpt4 book ai didi

javascript - 使用 Karma Jasmine 进行 Angular JS 测试

转载 作者:数据小太阳 更新时间:2023-10-29 03:55:30 27 4
gpt4 key购买 nike

我有一个像这样的示例路线:

  angular
.module('appRouter',['ui.router'])
.config(function($stateProvider,$urlRouterProvider){
$stateProvider
.....
.....
.state('settings.account',{
url:'/account',
templateUrl:'templates/account.html',
controller:function(resolveData){
console.log(resolveData);
},
resolve:{
resolveData : function($http){
var root = 'https://jsonplaceholder.typicode.com';
return $http.get(root+'/posts/1').then(function(response){

return response.data;
});
}
}
});

.....

这只是一个测试 URL,我可以在其中在线获取示例 JSON 数据

https://jsonplaceholder.typicode.com/posts/1

我想测试状态。

  beforeEach(function(){
module('appRouter');
});

beforeEach(inject(function(_$rootScope_,_$injector_,_$state_,_$httpBackend_,$templateCache){
$rootScope = _$rootScope_;
$state = _$state_;
$injector = _$injector_;
$httpBackend = _$httpBackend_;
$templateCache.put('templates/account.html','');
}));

it('should resolve "resolveData"',function(){
const state = $state.get('settings.account');
const resolveFn = state.resolve.resolveData;

$httpBackend.whenGET('https://jsonplaceholder.typicode.com/posts/1').respond(function(){
return [
200,{
"userId": 1,
"id": 1,
"title": "...",
"body": "..."
}]
});

$httpBackend.expectGET('https://jsonplaceholder.typicode.com/posts/1');

$injector.invoke(resolveFn);

$httpBackend.flush();

expect($injector.annotate(resolveFn)).toEqual(['$http']);

console.log(angular.mock.dump($scope));

expect($scope.resolveData).toEqual({
"userId": 1,
"id": 1,
"title": "...",
"body": "..."
});

但这失败了。说

1) should resolve "resolveData"
UI Routerer Config For Account
Expected undefined to equal Object({ userId: 1, id: 1, title: '...', body: '...' }).
at Object.<anonymous> (test/controllers/main-controller-spec.js:114:36)

我做错了什么?

更新

console.log(angular.mock.dump($scope)); 给出以下内容

enter image description here

请帮忙。

最佳答案

原始错误:

should resolve "resolveData"
UI Routerer Config For Account
TypeError: Cannot read property 'get' of undefined
at resolveData (app/appRouter.js:25:41)
at Object.<anonymous> (test/controllers/main-controller-spec.js:97:9)

What am I doing wrong?

您正在调用 resolveFn()在你的单元测试中。该函数被定义为需要 $http服务,并且该调用未通过 $http服务(如 fingerpich 所述)。

要更正此问题,允许 Angular 使用 $injector.invoke(resolveFn) 处理依赖项注入(inject).

使用 plunk 查看此操作.请注意,测试确实因不同的原因而失败。但是,(如果我正确理解规则)这是一个不同的问题,应该用不同的问题来回答(如果您需要更多帮助)。

旁注:当网站(不是单元测试)在浏览器中打开时,我希望它能正常工作,因为 Angular 注入(inject)了 $http依赖于分配给 resolveData 的函数.

answer这也引用了 fingerpich 提到的博客.

这是我在了解 unit testing AngularJS 时发现有用的博客.

关于javascript - 使用 Karma Jasmine 进行 Angular JS 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41843597/

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