Assets Not Loading in Ionic Unit Tests

December 27th 2019 Ionic 4+ Unit Testing Angular

Recently I had to embed a JSON file as an asset in my Ionic 4 project. When I tried to test the code accessing the asset, I was unpleasantly surprised. The JSON deserialization failed with:

SyntaxError: Unexpected token N in JSON at position 0

After further investigation I determined that the error occurred because the asset failed to load with a 404 error. The body of the response was NOT FOUND.

To see if I encountered a bug that was already fixed, I tried to reproduce it with a simple test using the latest version of Ionic CLI (5.4.13) and Angular CLI (8.3.21):

it('should load asset', async () => {
  const response = await fetch('./assets/sample.json');
  const json = await response.json();
  expect(json.success).toBeTruthy();
});

You can probably already guess the contents of my sample.json file:

{
  "success": true
}

The test still failed in Ionic but succeeded in Angular. By searching through the fixed Angular CLI bugs I could identify the one affecting me. Because of a bug in copy-webpack-plugin the backslash path separators on Windows weren't handled correctly.

Since the bug was already fixed, I only needed to update the @angular-devkit/build-angular dependency from version ~0.801.2 to version ~0.802.2:

npm install @angular-devkit/build-angular@~0.802.0

With the newer version installed, both the sample test and the real test I wrote to test my application code now worked.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License