Get json file for karma unit test

倖福魔咒の 提交于 2019-11-29 12:35:45

There are many ways to do that:

  • import json if it is inside of your app: import * as json from './test'; //will import test.json
  • download file using Http and do map(res=>res.json())
  • for webpack use json-loader plugin: var json = require('./my.json')
  • for gulp/grunt etc. you could write code generator

I stash my Mock JSON data into a ts file like a variable. i.e

export var getMockResponseJSON = { 'key': value };

Later when I want to reach this variable, I simply import it like:

import {getMockResponseJSON} from "../JSONs";

and use it in my class

expect(getMockResponseJSON.key).not.toEqual(1);

You could leverage the Http class of Angular2 within your tests to do that.

Here is a sample within a beforeAll function:

beforeAll((done) => {
  let injector = Injector.resolveAndCreate([ HTTP_PROVIDERS ]);
  let http = injector.get(Http);
  http.get('app/data.json').subscribe(
    (data) => {
      this.data = data.json();
      done();
    }
  );
});

See this plunkr: https://plnkr.co/edit/k6jxHf?p=preview.

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