This question already has an answer here:
这个问题在这里已有答案:
- Load local JSON into Jasmine/Karma Unit Test in AngularJS 2 answers
- 在AngularJS 2答案中将本地JSON加载到Jasmine / Karma单元测试中
I'm writing some tests for an Angular 2 app that needs to mock a big JSON structure. I want to put that that JSON in its own file so that I can import it on other tests as well. In using Jasmine with Karma.
我正在为一个需要模拟大型JSON结构的Angular 2应用程序编写一些测试。我想将JSON放在自己的文件中,以便我也可以在其他测试中导入它。使用Jasmine和Karma。
Any ideas on how to solve this?
关于如何解决这个问题的任何想法?
1 个解决方案
#1
2
A couple of options:
有两种选择:
- Put the JSON in a javascript file (as a global variable) and load that javascript file by adding an "include" in your karma configuration file.
- 将JSON放在javascript文件中(作为全局变量)并通过在karma配置文件中添加“include”来加载该javascript文件。
- Use a script loader (such as requirejs or another AMD script loader) to load your js file.
- 使用脚本加载器(例如requirejs或其他AMD脚本加载器)来加载js文件。
- Add a service or constant to your angular module in a standalone javascript file, then you should be able to retrieve it from your test file.
- 在独立的javascript文件中为角度模块添加服务或常量,然后您应该能够从测试文件中检索它。
The best option probably depends on how you are loading your scripts at the minute. Assuming the Angular code is split into multiple files, how do you ensure all the files are loaded?
最佳选择可能取决于您何时加载脚本。假设Angular代码被拆分为多个文件,您如何确保加载所有文件?
If you just import the files manually in the correct order and use the global variable window.angular to define your modules, then option 1 or 3 is best. If you already use an AMD loader then option 2 is worth considering.
如果您只是以正确的顺序手动导入文件并使用全局变量window.angular来定义模块,那么最好使用选项1或3。如果您已经使用AMD加载器,则选项2值得考虑。
#1
2
A couple of options:
有两种选择:
- Put the JSON in a javascript file (as a global variable) and load that javascript file by adding an "include" in your karma configuration file.
- 将JSON放在javascript文件中(作为全局变量)并通过在karma配置文件中添加“include”来加载该javascript文件。
- Use a script loader (such as requirejs or another AMD script loader) to load your js file.
- 使用脚本加载器(例如requirejs或其他AMD脚本加载器)来加载js文件。
- Add a service or constant to your angular module in a standalone javascript file, then you should be able to retrieve it from your test file.
- 在独立的javascript文件中为角度模块添加服务或常量,然后您应该能够从测试文件中检索它。
The best option probably depends on how you are loading your scripts at the minute. Assuming the Angular code is split into multiple files, how do you ensure all the files are loaded?
最佳选择可能取决于您何时加载脚本。假设Angular代码被拆分为多个文件,您如何确保加载所有文件?
If you just import the files manually in the correct order and use the global variable window.angular to define your modules, then option 1 or 3 is best. If you already use an AMD loader then option 2 is worth considering.
如果您只是以正确的顺序手动导入文件并使用全局变量window.angular来定义模块,那么最好使用选项1或3。如果您已经使用AMD加载器,则选项2值得考虑。