How to load mock data from JSON file in Angular 2 karma jasmine test?
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
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();
});