gpt4 book ai didi

AngularJS:单元测试 Controller 返回 "TypeError: $scope.$watch is not a function"

转载 作者:行者123 更新时间:2023-12-02 10:21:42 25 4
gpt4 key购买 nike

我想为 Controller 编写一个简单的测试

  • sets a variable of the scope to an ID
  • calls a function that triggers an API call with the ID on the scope
  • log the result
    describe('The app', () => {

beforeEach(angular.mock.module('myModule'));

var $controller;
var eId = 123456;

beforeEach(angular.mock.inject((_$controller_) => {
$controller = _$controller_;
}));


describe('directive', () => {
it('should load the data from the api', () => {
var scope = {};
var controller = $controller('myController', { $scope: scope });
scope.entityId = eId;
expect(scope.entityId).toBe(eId);

controller.load(); // API call using scope.entityId, to load some data into the scope
scope.$digest();
console.log("entities:", controller.entities); // Where the data should be loaded into
});
});
});

我的 Controller 使用“controller as”语法。

我的测试是使用 karma 运行的,它返回了以下错误:

TypeError: $scope.$watch is not a function | at myController.watchChanges

非常感谢任何正确方向的提示!

最佳答案

您创建了一个像空对象一样的范围,这并不正确。您应该像创建 $rootScope 的新实例一样创建它。查看代码示例:

 describe('The app', () => {

beforeEach(angular.mock.module('myModule'));

var $controller, $rootScope;
var eId = 123456;

beforeEach(angular.mock.inject((_$controller_, _$rootScope_) => {
$controller = _$controller_;
$rootScope = _$rootScope_;
}));


describe('directive', () => {
it('should load the data from the api', () => {
var scope = $rootScope.$new();
var controller = $controller('myController', { $scope: scope });
scope.entityId = eId;
expect(scope.entityId).toBe(eId);

controller.load(); // API call using scope.entityId, to load some data into the scope
scope.$digest();
console.log("entities:", controller.entities); // Where the data should be loaded into
});
});
});

希望对您有帮助!

关于AngularJS:单元测试 Controller 返回 "TypeError: $scope.$watch is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36713555/

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