如何在Angular 2 Karma茉莉测试中从JSON文件加载模拟数据? [英] How to load mock data from JSON file in Angular 2 karma jasmine test?

查看:159
本文介绍了如何在Angular 2 Karma茉莉测试中从JSON文件加载模拟数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 angular 2

我们遇到了在单独的JSON文件中模拟数据的要求,因为数据量很大(希望确保代码的整洁度).为此,我进行了很多搜索,但没有找到合适的解决方案.

And we came across requirement to mock data in separate JSON file as data is huge (want to make sure code cleanness). For this I searched a lot but didn't find proper solution.

我们已经使用 MockBackend 来模拟HTTP服务,因此我们不能使用angular的HTTP服务来加载JSON,因为最终请求将传递给MockBackend.

We already mocking HTTP service using MockBackend, So we can't use HTTP service of angular to load JSON as it eventually request will go to MockBackend.

那么还有其他方法可以不使用任何第三方库吗? jasmine-jquery还是Karma-jasmine-preprocessor? 更多种Angular JS 2方式 .

So is there any another way without using any third party lib like jasmine-jquery or Karma-jasmine-preprocessor ? More kind of Angular JS 2 way.

推荐答案

我遇到了同样的问题!

最后,我意识到仅在TypeScript中直接使用require()函数就可以了. Node和@ types/node支持它,否则有些需要声明require类型.

Finally, I realized that just using the require() function directly in TypeScript works just fine. It is supported by Node and @types/node, otherwise some need to declare require types.

因此要在Angular 2 Karma Jasmine测试中从JSON文件加载模拟数据,请执行以下操作:

So to load mock data from JSON file in Angular 2 Karma Jasmine test, go for:

const data: any = require('../../assets/mock-data.json');

PS:获得Artur Ampilogov的积分

这篇关于如何在Angular 2 Karma茉莉测试中从JSON文件加载模拟数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆