gpt4 book ai didi

javascript - 使用 Jasmine 测试 Angular Controller (方法/服务调用)

转载 作者:行者123 更新时间:2023-11-28 06:46:11 25 4
gpt4 key购买 nike

我正在尝试使用 Jasmin 测试用 AngularJS 编写的小型 Controller 。

(function() {
'use strict';
angular
.module('bsp.account')
.controller('Account', Account);

/* @ngInject */
function Account(userService, accountService) {

var vm = this;

vm.title = 'Account';

vm.username = userService.getUsername();
vm.showPasswordModal = accountService.showPasswordModal;
vm.showLogoutModal = accountService.showLogoutModal;
}
})();

我想测试 vm.username ,vm.showPersonModal 和 vm.showLogoutModal 。这些都是对 Controller 中注入(inject)的服务的引用。我是个新手,正在慢慢尝试在测试中建立我的概念。下面是现在运行的测试用例,

describe('Account', function() {
var scope, controller, userServiceMock,accountServiceMock;
beforeEach(module('bsp'));
beforeEach(function() {
userServiceMock = {
getUsername: function(){}
};
accountServiceMock = {
showPasswordModal :function(){}
};
});

beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('Account', {
'userService': userServiceMock,
'accountService':accountServiceMock
});
}));

describe('testing Title',function(){
it('checkTitle', function(){
expect(controller.title).toEqual('Account');
});
});


});

感谢您的所有建议

最佳答案

我能看到的唯一问题是

  1. 您引导了错误的模块(应该是 'bsp.account' 而不是 'bsp')
  2. 您尚未提供测试您的服务方法是否被调用的方法

您可以使用spies来解决后者。 。例如

describe('Account', function() {
var controller, userServiceMock, accountServiceMock;

beforeEach(function() {
module('bsp.account');

userServiceMock = jasmine.createSpyObj('userService', ['getUsername']);
userServiceMock.getUsername.and.returnValue('testUser');

accountServiceMock = jasmine.createSpyObj('accountService', ['showPasswordModal', 'showLogoutModal']);

inject(function($controller) {
controller = $controller('Account', {
userService: userServiceMock,
accountService: accountServiceMock
});
});
});

it('assigns values from services', function() {
expect(userServiceMock.getUsername).toHaveBeenCalled();
expect(controller.username).toEqual('testUser');
expect(controller.showPasswordModal).toBe(accountServiceMock.showPasswordModal);
expect(controller.showLogoutModal).toBe(accountServiceMock.showLogoutModal);
});
});

关于javascript - 使用 Jasmine 测试 Angular Controller (方法/服务调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33403295/

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