javascript - 我的应用程序中的单元测试问题

标签 javascript angularjs unit-testing jasmine

我在加载 $resource 对象时遇到问题。

我在父 Controller 中有一些东西

$scope.data = Product.$query();

然后在子 Controller 中,我有

$scope.data.$promise.then(function(product){
     console.log(data);
})

我的工厂

angular.module('testApp').factory('Product', ['$resource', function ($resource) {
    return $resource('/api/product');
}]);

我将 Product.$query() 放在父 Controller 中的原因是因为我希望它在不同的子 Controller 中共享和使用。

我的测试文件如下

describe('Product test ', function () {
    var $httpBackend, childCtrl,  scope;

    beforeEach(module('testApp', function($provide) {
        $provide.value('$log', console);
    }));

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
        scope = _$rootScope_.$new();
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;

        childCtrl = _$controller_('childCtrl', {
            $scope: scope
        });
    }));

    describe('some test', function() {
        it('some test here', function(){
             //codes...
        })
    })
});

当我运行测试时,我得到了

TypeError: 'undefined' is not an object (evaluating '$scope.data.$promise')

我不确定这里发生了什么。有人可以帮我吗?非常感谢

最佳答案

因为我要在 jasmine 中测试 $resource 对象,你需要创建你的 $httpBackend 模拟响应,当你查询 时它会返回$resource 你不应该直接使用`$resource。

describe('Product test ', function () {
    var $httpBackend, childCtrl,  scope, Product;

    beforeEach(module('testApp', function($provide) {
        $provide.value('$log', console);
    }));

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, Product) {
        scope = _$rootScope_.$new();
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;
        Product = Product;

        childCtrl = _$controller_('childCtrl', {
            $scope: scope,
            Product: Product
        });
    }));

    describe('some test', function() {
        it('some test here', function(){
             $httpBackend.expect('GET', '/api/product').respond([{ id: 1, name: 'a' }, { id: 2, name: 'b' }]);
             childCtrl.data = Product.query();
                 expect(childCtrl.projects).toEqualData([]);
                 $httpBackend.flush(); //flushing $httpBackend
                 expect(childCtrl.data).toEqualData([{ id: 1, name: 'a' }, { id: 2, name: 'b' }]);
        })
    })
});

更多详情可以引用this link

关于javascript - 我的应用程序中的单元测试问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086963/

相关文章:

javascript - THREE.CameraDolly 不是构造函数(Three.js 和 dolly.js)

javascript - 关闭和事件

angularjs - angular-resource.js 编码UriSegment 问题

ajax - AngularJS : single page and multipage app difference and use in practice?

unit-testing - 如何在 Netbeans 中分析单元测试?

javascript - React Hooks 无限循环

javascript - 如何使用javascript检查视口(viewport)是否小于特定宽度?

html - 如何通过将图像堆叠在 div 中来在图像上设置功能区?

c# - 当结果以 IActionResult 类型返回时,如何在 Xunit 中获取内容值

java - 如何在测试类中模拟 JNDI 数据源