Get json file for karma unit test - json

I want to get a JSON file in my unit test because I need to have it for my tests but I dont know how I can include the file
I run my test with karma and Jasmine. And my project is created with Angular 2.
The name of my JSON file is 'www/assets/mocks/emptyCalendarData.JSON'.
Does someone know how I can include a JSON file into a spec file?
Thanks
UPDATE
I tried to use HTTP get but then I got a system
let calendarData: Calendar;
http.get('www/assets/mocks/emptyCalendarData.json')
.map(res => res.json())
.subscribe(
data => calendarData = data,
err => console.log(JSON.stringify(err))
);
Then I get this error:
ERROR: Error{stack: null, originalErr: TypeError{stack: 'mergeOptions
get
eval code
eval#[native code]
__exec#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:1482:16
execute#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:3896:22
linkDynamicModule#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:3222:36
link#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:3065:28
execute#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:3402:17
doDynamicExecute#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:796:32
link#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:998:36
doLink#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:650:11
updateLinkSetOnLoad#http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:698:24
http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624:510:30
invoke#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:364:34
run#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:257:50
http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:609:61
invokeTask#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:397:43
runTask#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:294:58
drainMicroTaskQueue#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:515:43
invoke#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:467:41
http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:92:33
invokeTask#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:397:43
runTask#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:294:58
invoke#http://localhost:9876/base/node_modules/zone.js/dist/zone.js?b9a84410301a475a439d6b7b4e7eff0954f5b925:464:41', line: 38}, line: 821, sourceURL: 'http://localhost:9876/base/node_modules/systemjs/dist/system.src.js?18a094f61af9f2ec0577ca3a337760d97719b624'}

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.

Related

NextJs Webpack asset/source returns JSON as a string

Looking for some help to understand what is going on here.
The Problem
We are using a translation service that requires creating JSON resource files of copy, and within these resource files, we need to add some specific keys that the service understands so it knows what should and should not be translated.
To do this as simple as possible I want to import JSON files into my code without them being tree shaken and minified. I just need the plain JSON file included in my bundle as a JSON object.
The Solution - or so I thought
The developers at the translation service have instructed me to create a webpack rule with a type of assets/source to prevent tree shaking and modification.
This almost works but the strange thing is that the JSON gets added to the bundle as a string like so
module.exports = "{\n \"sl_translate\": \"sl_all\",\n \"title\": \"Page Title\",\n \"subtitle\": \"Page Subtitle\"\n}\n";
This of course means that when I try and reference the JSON values in my JSX it fails.
Test Repo
https://github.com/lukehillonline/nextjs-json-demo
NextJs 12
Webpack 5
SSR
Steps To Reproduce
Download the test repo and install packages
Run yarn build and wait for it to complete
Open /.next/server/pages/index.js to see the SSR page
On line 62 you'll find the JSON object as a string
Open .next/static/chunks/pages/index-{HASH}.js to see the Client Side page
If you format the code you'll find the JSON object as a string on line 39
Help!
If anyone can help me understand what is going wrong or how I can improve the webpack rule to return a JSON object rather than a string that would be a massive help.
Cheers!
The Code
next.config.js
module.exports = {
trailingSlash: true,
productionBrowserSourceMaps: true,
webpack: function (config) {
config.module.rules.push({
test: /\.content.json$/,
type: "asset/source",
});
return config;
},
};
Title.content.json
{
"sl_translate": "sl_all",
"title": "Page Title",
"subtitle": "Page Subtitle"
}
Title.jsx
import content from "./Title.content.json";
export function Title() {
return <h1>{content.title}</h1>;
}
pages/index.js
import { Title } from "../components/Title/Title";
function Home({ dummytext }) {
return (
<div>
<Title />
<p>{dummytext}</p>
</div>
);
}
export const getServerSideProps = async () => {
const dummytext = "So we can activate SSR";
return {
props: {
dummytext,
},
};
};
export default Home;

How to use 'require' to import a JSON in NestJS controller?

I'm trying to return a json file as a controller response, but I can't get the content of the json.
import { Controller, Get, Res, HttpStatus, Query } from '#nestjs/common';
import { Response } from 'express';
import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file is imported fine
const MOCKED_RESPONSE = require('./data/payment-method-mock'); // this json file is not found
#Controller('commons')
export class CommonController {
#Get('/payment-method')
getPaymentMoethod(#Res() res: Response): any {
res.status(HttpStatus.OK).send(MOCKED_RESPONSE);
}
}
Actually the log returns: Error: Cannot find module './data/payment-method' and the app doesn't compile
I have done this with express (even with typescript) and works fine.
I don't know if i have to setup my project to read jsons (I'm newby on nest). By the moment I have created a typescript file exporting a const with the json content and I called it successfuly
I guess the problem lies in the way you import your .json file (change import instead of const)
Another advice or solution would be to leverage the .json() method of the res object (which is actually the express adapter response object).
Let's try with this code:
Your common.controller.ts file:
import { Controller, Get, Res, HttpStatus, Query } from '#nestjs/common';
import { Response } from 'express';
import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file should still be imported fine
import * as MOCKED_RESPONSE from './data/payment-method-mock.json'; // or use const inside the controller function
#Controller('commons')
export class CommonController {
#Get('/payment-method')
getPaymentMoethod(#Res() res: Response): any {
res.status(HttpStatus.OK).json(MOCKED_RESPONSE); // <= this sends response data as json
}
}
Also in your tsconfig.json file, don't forget to add this line:
tsconfig.json
{
"compilerOptions": {
// ... other options
"resolveJsonModule": true, // here is the important line, this will help VSCode to autocomplete and suggest quick-fixes
// ... other options
}
Last thoughts: you could use the sendfile() method of the res object depending on whether you want to send back a json file or the content of your json file.
Let me know if it helps ;)
first make sure you are calling it correctly.
Are you getting any response at all? if not double check your method name since its spelled like this: getPaymentMoethod and it should be this: getPaymentMethod.
Secondly I would recommend requiring outside the method and setting it to a constant.
Lastly try wrapping it in JSON.stringify() to convert the response to a json stringified object

How to parse external JSON file in the .jsx file

I'm new with React and need some one with my json file Parsing problem. I am having a PerfCompare.jsx with a variable needed in the following compare. And i need this var parsing from a external JSON file(trscConfig.JSON). I am using this lines to do. but always get this SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
trscConfig.JSON
{
"server" : "http://myserver.com"
}
PerfCompare.jsx
import React, { Component } from 'react';
import { Form, Input, Button, Radio, Row, Table, Divider, Progress, Alert } from 'antd';
import math from 'mathjs';
import { stringify } from 'qs';
import PerffarmRunJSON from './lib/PerffarmRunJSON';
import JenkinsRunJSON from './lib/JenkinsRunJSON';
import benchmarkVariantsInfo from './lib/benchmarkVariantsInfo';
import './PerfCompare.css';
//import App_DATA from './trscConfig.JSON';
const server_2 = JSON.parse('./trscConfig.JSON').server;
Use fetch():
const response = await fetch('trscConfig.JSON');
const json = await response.json();
const server_2 = json.server;
Or, if your build tool doesn't support await yet:
fetch('trscConfig.JSON')
.then(response => response.json())
.then(json => {
const server_2 = json.server;
});
In either case, downloading the JSON file at runtime will mean the response will not be available immediately. If this is a React component, I suggest doing this in componentDidMount().
Alternatively, if the JSON file is a static asset:
import {server as server_2} from './trscConfig.JSON';
JSON.parse doesn't know how to make HTTP requests/read files - it just parses exactly what you've passed in. In this case, it's failing because it's trying to convert the literal string ./trscConfig.JSON into a JSON object!
There's two ways you could get this working:
Load in the JSON via your module bundler, as you're doing in the commented out line in your code. I believe Webpack (and most others) support this out of the box, but your configuration might have it disabled, intentionally or otherwise. It might also be because you're using uppercase file extensions - try it with a file that has .json in lowercase.
Use XMLHttpRequest, the Fetch API, or a third-party HTTP client library to download the JSON at runtime, and then parse the downloaded text.

Loading JSON Without an HTTP Request

I am working on a project using Angular 4, NPM, Node.js, and the Angular CLI.
I have a rather unusual need to load JSON into an Angular service (using an #Injectable) without an HTTP request, i.e. it will always be loaded locally as part of the package, and not retrieved from a server.
Everything I've found so far indicates that you either have to modify the project's typings.d.ts file or use an HTTP request to retrieve it from the /assets folder or similar, neither of which is an option for me.
What I am trying to accomplish is this. Given the following directory structure:
/app
/services
/my-service
/my.service.ts
/myJson.json
I need the my.service.ts service, which is using #Injectable, to load the JSON file myJson.json. For my particular case, there will be multiple JSON files sitting next to the my.service.ts file that will all need to be loaded.
To clarify, the following approaches will not work for me:
Using an HTTP Service to Load JSON File From Assets
URL: https://stackoverflow.com/a/43759870/1096637
Excerpt:
// Get users from the API
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
Modifying typings.d.ts To Allow Loading JSON Files
URL: https://hackernoon.com/import-json-into-typescript-8d465beded79
Excerpt:
Solution: Using Wildcard Module Name
In TypeScript version 2 +, we can use wildcard character in module name. In your TS definition file, e.g. typings.d.ts, you can add this line:
declare module "*.json" {
const value: any;
export default value;
}
Then, your code will work like charm!
// TypeScript
// app.ts
import * as data from './example.json';
const word = (<any>data).name;
console.log(word); // output 'testing'
The Question
Does anyone else have any ideas for getting these files loaded into my service without the need for either of these approaches?
You will get an error if you call json directly, but a simple workaround is to declare typings for all json files.
typings.d.ts
declare module "*.json" {
const value: any;
export default value;
}
comp.ts
import * as data from './data.json';
The solution I found to this was using RequireJS, which was available to me via the Angular CLI framework.
I had to declare require as a variable globally:
declare var require: any;
And then I could use require.context to get all of the files in a folder I created to hold on the types at ../types.
Please find below the entire completed service that loads all of the JSON files (each of which is a type) into the service variable types.
The result is an object of types, where the key for the type is the file name, and the related value is the JSON from the file.
Example Result loading files type1.json, type2.json, and type3.json from the folder ../types:
{
type1: {
class: "myClass1",
property1: "myProperty1"
},
type2: {
class: "myClass2",
property1: "myProperty2"
},
type3: {
class: "myClass3",
property1: "myProperty3"
}
}
The Final Service File
import { Injectable } from '#angular/core';
declare var require: any;
#Injectable()
export class TypeService {
constructor(){
this.init()
};
types: any;
init: Function = () => {
// Get all of the types of branding available in the types folder
this.types = (context => {
// Get the keys from the context returned by require
let keys = context.keys();
// Get the values from the context using the keys
let values = keys.map(context);
// Reduce the keys array to create the types object
return keys.reduce(
(types, key, i) => {
// Update the key name by removing "./" from the begining and ".json" from the end.
key = key.replace(/^\.\/([^\.]+)\.json/, (a, b)=> { return b; });
// Set the object to the types array using the new key and the value at the current index
types[key] = values[i].data;
// Return the new types array
return types;
}, {}
);
})(require.context('../types', true, /.json/));
}
}
You can directly access variables in services from their object that is defined in the constructor.
...So say your constructor loads the service like this
constructor(private someService:SomeService){}
You can just do someService.theJsonObject to access it.
Just be careful not to do this before it gets loaded by the service function that loads it. You'd then get a null value.
You can assign variables to your service files the same way you do in component files.
Just declare them in the service
public JsonObject:any;
And (easiest way) is to let the function that called your service assign the JSON object for you.
So say you called the service like this
this.serviceObject.function().subscribe
(
resp =>
{
this.serviceObject.JsonObject = resp;
}
);
After this is done once, other components can access that JSON content using someService.theJsonObject as discussed earlier.
In your case I think all you need to do is embed your JSON object in your code. Maybe you can use const. That's not bad code or anything.

Angular 2 - how to fill a local variable with JSON data from an external file

The Angular 2 tutorials I have read place variables directly in the app.component.ts file. For example var BAR below, which pulls data though the {Foo} interface.
import {Component} from 'angular2/core';
import {Foo} from './foo';
#Component({
etc.
});
export class AppComponent {
bar = BAR;
}
var BAR: Foo[] = [
{ 'id': 1 },
{ 'id': 2 }
];
However, I have the data for BAR in a local JSON file. I don't believe {HTTP_PROVIDER} is necessary. How would I go about getting the JSON data from the external file?
Create a file with this content
export const BAR= [
{ 'id': 1 },
{ 'id': 2 }
];
save it as BarConfig.ts or some like
later use it as follows
import { BAR } from './BarConfig';
let bar= BAR;
or even better, use BAR directly where you needed
HTTP_PROVIDER is needed if you want to load a file using http.
Here is an example of how to load a local json file over http:
this.result = {friends:[]};
this.http.get('./friends.json').map((res: Response) => res.json()).subscribe(res => this.result = res);
More details here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
Juste put your .json file in your static folder (/assets if you are using the angular cli) and it should work.
Best option is to create json file and store json details inside file and call that file using like below.
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
return this.http.get('<json file path inside assets folder>.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.
You can use the Http provider in angular2
Make sure you place your local json file in the www folder.
getLocalFile(){
return this.http.get('./localFileName.json').
map(res => res.json());
}
This will return you the local JSON file.