无法在ANgularJS中为Controller编写Jasmine测试用例

时间:2013-12-16 10:12:27

标签: angularjs jasmine angularjs-controller

我的控制器中有以下代码,我想为此部分编写Jasmine测试用例。     我试着写一个,但它抛出以下错误         TypeError:Object [object Array]没有方法'then'

控制器代码::

$scope.doGetList = function() {
                var queryString = {......sending some query parameters};
                searchResource.getList(queryString).then(
                    function (data) {
                        $scope.sugesstions = data;
                    }
                );
            };

茉莉花测试案例::

it("should return provided list", angular.mock.inject(function($rootScope, $controller) {
                            var scope = $rootScope.$new();

                            var searchResource = {
                                getList: function() {
                                    return ['suggestions1', 'suggestions2', 'suggestions3'];
                                }
                            };

                            $controller(
                                    headerController,
                                    {
                                        $scope: scope,
                                        cartsService: null,
                                        currentUser: null,
                                        searchResource: searchResource
                                    }
                            );

                            expect(scope.sugesstions).toBeDefined();
                            expect(scope.sugesstions.length).toBe(0);

                            //this method will call mock method instead of actual server call
                            scope.doGetAutocomplete();
                            expect(scope.sugesstions.length).toBe(3);
                            expect(scope.sugesstions[0]).toEqual('suggestions1');
                            expect(scope.sugesstions[1]).toEqual('suggestions2');
                            expect(scope.sugesstions[2]).toEqual('suggestions3');
                        }));

我该怎么写呢。

1 个答案:

答案 0 :(得分:1)

您必须在runs()中包装异步调用。来自jasmine doc:http://pivotal.github.io/jasmine/#section-Asynchronous_Support

或者,我使用茉莉花作为承诺提供更好的支持:https://github.com/ThomasBurleson/jasmine-as-promised