如何在Angular 2中将外部JSON文件加载到我的测试中? [重复]

时间:2023-01-24 11:32:45

This question already has an answer here:

这个问题在这里已有答案:

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值得考虑。