How to load mock data from JSON file in Angular 2 karma jasmine test?

你离开我真会死。 提交于 2019-12-05 21:43:54

问题


I writing karma jasmine test case for angular 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.

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.

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.


回答1:


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.

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: credits to Artur Ampilogov




回答2:


i'm trying to do the same, system.import works if you pass path of the JSON like this

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);
    });`


来源:https://stackoverflow.com/questions/42129039/how-to-load-mock-data-from-json-file-in-angular-2-karma-jasmine-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!