单元测试时如何处理angular模块的配置功能? [英] How to deal with angular module's config function when unit testing?
问题描述
在使用 Karma/Jasmine 为 Angular 应用程序设置单元测试套件时,是否建议将 js 与应用模块的 config
函数一起包含在测试文件中?
When setting up a unit test suite for an angular application using Karma/Jasmine, is it recommended to include the js with the app module's config
function in the test's files?
我读到建议将其排除在测试之外,但这似乎很尴尬,因为在 config
函数中经常会发生关键设置,这会阻止应用程序工作.
I've read that it is suggested to exclude this from testing, however that seems awkward because there's often critical setup that happens in the config
function that would prevent the application from working.
这方面的最佳做法是什么?创建一个以模拟"方式执行相同操作的模拟配置函数?
What's the best practice around this? Create a mock config function that does the same thing in a 'mocked' manner?
我自己也遇到了这个问题,但想了解更广泛的策略:如何使用angular-translate进行单元测试
I'm running across this issue myself but want to understand the broader strategy: How do unit test with angular-translate
推荐答案
在我的应用程序中,我最终使用了以下解决方案:
In my application, I ended up using the following solution:
定义一个包含所有 config
和 run
函数的appBase"模块,我想在单元测试时运行这些函数并创建另一个声明appBase"的app"模块" 模块作为依赖项,包括所有的 config
和 run
函数,我不知道在单元测试时要运行什么.然后我所有的单元测试都使用appBase"模块,而最终的应用程序使用app"模块.在代码中:
Define an "appBase" module with all the config
and run
functions that I want to run when unit-testing and create another "app" module which declares "appBase" module as a dependency and includes all the config
and run
functions that I don't what to run when unit-testing. Then all my unit tests use the "appBase" module, while the final application uses the "app" module. In code:
angular.module('appBase', ['dependencies'])
.config(function() {
// This one will run when unit-testing. Can also set-up mock data
// that will later be overridden by the "app" module
});
angular.module('app', ['appBase'])
.config(function() {
// This function will only run in real app, not in unit-tests.
});
这篇关于单元测试时如何处理angular模块的配置功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!