[AngularJS] Test an Angular Component with $componentController
Traditionally you had to create DOM elements to test a directive but by shifting our focus to components, writing unit tests got a lot easier using $componentControllerwithin ngMocks. We can now test our component's controller with an easy to use API that does not require us to spin up any DOM elements to do so. In this lesson, we will see how our ES6 tests are transpiled, learn how to test a component using$componentController and talk about how to simulate lifecycle hooks.
Controller:
class CategoriesController { constructor(CategoriesModel) { 'ngInject'; this.CategoriesModel = CategoriesModel; } $onInit() { this.CategoriesModel.getCategories() .then(result => this.categories = result); } onCategorySelected(category) { this.CategoriesModel.setCurrentCategory(category); } isCurrentCategory(category) { return this.CategoriesModel.getCurrentCategory() && this.CategoriesModel.getCurrentCategory().id === category.id; } } export default CategoriesController;
Test:
import CategoriesModule from './categories'; import CategoriesController from './categories.controller'; import CategoriesComponent from './categories.component'; import CategoriesTemplate from './categories.html'; describe('Categories', () => { let component, $componentController, CategoriesModel; beforeEach(() => { window.module('categories'); window.module($provide => { $provide.value('CategoriesModel', { getCategories: () => { return { then: () => {} }; } }); }); }); beforeEach(inject((_$componentController_, _CategoriesModel_) => { CategoriesModel = _CategoriesModel_; $componentController = _$componentController_; })); describe('Module', () => { it('is named correctly', () => { expect(CategoriesModule.name).toEqual('categories'); }); }); describe('Controller', () => { it('calls CategoriesModel.getCategories immediately', () => { spyOn(CategoriesModel, 'getCategories').and.callThrough(); component = $componentController('categories', { CategoriesModel }); component.$onInit(); expect(CategoriesModel.getCategories).toHaveBeenCalled(); }); });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-09-08 [AngularJS + Webpack] Requiring CSS & Preprocessors
2015-09-08 [AngularJS + Webpack] Requiring Templates
2015-09-08 [AngularJS + Webpack] ES6 with BabelJS