I writing karma jasmine test case for angular 2,
我为角2写了业力茉莉花测试案例,
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.
我们遇到了在单独的JSON文件中模拟数据的要求,因为数据很大(想要确保代码清洁)。为此我搜索了很多,但没有找到适当的解决方案。
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.
我们已经使用MockBackend模拟HTTP服务,所以我们不能使用angular的HTTP服务加载JSON,因为它最终请求将转到MockBackend。
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.
那么有没有其他方法可以不使用任何第三方库,如jasmine-jquery或Karma-jasmine-preprocessor?更多种类的Angular JS 2方式。
2 个解决方案
#1
13
I had the same issue!
我遇到过同样的问题!
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.
最后,我意识到直接在TypeScript中使用require()函数就可以了。它受Node和@ types / node支持,否则有些需要声明require类型。
So to load mock data from JSON file in Angular 2 Karma Jasmine test, go for:
因此,要在Angular 2 Karma Jasmine测试中从JSON文件加载模拟数据,请转到:
const data: any = require('../../assets/mock-data.json');
PS: credits to Artur Ampilogov
PS:Artur Ampilogov的学分
#2
0
i'm trying to do the same, system.import works if you pass path of the JSON like this
我正在尝试做同样的事情,如果你像这样传递JSON的路径,system.import就可以了
example :
例子:
`System.import('../../assets/mock-data/mock-data.json')
.then((json) => {
console.log(json);
});`
what is really weird, is that I didn't manage to make it work with variables. example :
真正奇怪的是,我没有设法让它与变量一起工作。例子:
`let myUrl: string = '../../assets/mock-data/mock-data.json';
System.import(myUrl)
.then((json) => {
console.log(json);
});`
#1
13
I had the same issue!
我遇到过同样的问题!
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.
最后,我意识到直接在TypeScript中使用require()函数就可以了。它受Node和@ types / node支持,否则有些需要声明require类型。
So to load mock data from JSON file in Angular 2 Karma Jasmine test, go for:
因此,要在Angular 2 Karma Jasmine测试中从JSON文件加载模拟数据,请转到:
const data: any = require('../../assets/mock-data.json');
PS: credits to Artur Ampilogov
PS:Artur Ampilogov的学分
#2
0
i'm trying to do the same, system.import works if you pass path of the JSON like this
我正在尝试做同样的事情,如果你像这样传递JSON的路径,system.import就可以了
example :
例子:
`System.import('../../assets/mock-data/mock-data.json')
.then((json) => {
console.log(json);
});`
what is really weird, is that I didn't manage to make it work with variables. example :
真正奇怪的是,我没有设法让它与变量一起工作。例子:
`let myUrl: string = '../../assets/mock-data/mock-data.json';
System.import(myUrl)
.then((json) => {
console.log(json);
});`