During my testing process, I encountered an issue when trying to require a .json file with data to perform checks on. Despite passing the string indicating where to find the file into the require function, it seems to be unsuccessful...
Success:
const data = require('../../../assets/data.json');
Failure:
const jsonUrl = '../../../assets/data.json';
const data = require(jsonUrl);
I prefer using the variable jsonUrl
as this URL string will need to be utilized multiple times within the test. However, I am perplexed as to why it is not locating the file?
Clarification of Inquiry:
Considering that mocking is the recommended approach in this situation, and my lack of understanding in executing this effectively... I have decided to make some adjustments to the question for clarity.
To my understanding in testing, I believe that it is essential to read in the actual data being used for accurate testing outcomes. If my assumption is incorrect, kindly advise me accordingly.
The following are details of what I am examining...
data.json
[
{
"name": "one",
"id": 1,
},
...
// This structure applies to around 20 entries
]
component.ts
ngOnInit() {
loadData().subscribe(data => {
this.data = data;
};
}
loadData() {
const statusUrl = '../../../assets/data.json';
return this.httpClient.get(statusUrl);
}
test.ts The issue relates to 'cannot find module' due to the require problem mentioned earlier.
it('should load status data from local json', fakeAsync(() => {
const jsonUrl = '../../../assets/status.json';
const data = require(jsonUrl);
const request = httpMock.expectOne(jsonUrl);
request.flush(data);
expect(component.status).toEqual(data);
}));