当前位置:  开发笔记 > 编程语言 > 正文

使用Karma Jasmine进行Angular JS测试

如何解决《使用KarmaJasmine进行AngularJS测试》经验,为你挑选了0个好方法。

我有这样的示例路线:

  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. (test/controllers/main-controller-spec.js:114:36)

我究竟做错了什么 ?

UPDATE

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

在此输入图像描述

请帮忙.

推荐阅读
手机用户2502851955
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有