Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am 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.

like image 361
Viraj Avatar asked Feb 09 '17 05:02

Viraj


2 Answers

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

like image 73
Kaloyan Kosev Avatar answered Nov 19 '22 21:11

Kaloyan Kosev


You can configure the typescript compiler to load in json files, by specifying

--resolveJsonModule

Or by adding

"resolveJsonModule": true

to the compilerOptions property of tsconfig.json

Then, in your spec file, you can import the json file into a variable as follows:

import * as myJson from './test/myJson.json';

You can then access it in a test, e.g.:

it('it should let me access properties from my json file', () => {
    expect(myJson.myProperty).toBeTruthy();
});
like image 21
John Gamble Avatar answered Nov 19 '22 21:11

John Gamble