Cannot read property ‘range’ of undefined – Angular Tests Fail in Docker

Cannot read property ‘range’ of undefined – Angular Tests Fail in Docker

Hi there, today I’d like to share with you a little caveat that might result to the Angular Tests being successful on your local development machine but failing while on build server in Docker Container.

The text you might see does not give much sense about what might be causing an issue. Check it yourself:

ERROR [karma-server]: UnhandledRejection: Cannot read property 'range' of undefined
ERROR [karma-server]: TypeError: Cannot read property 'range' of undefined
    at handleRangeHeaders (/app/node_modules/webpack-dev-middleware/lib/util.js:131:21)
    at processRequest (/app/node_modules/webpack-dev-middleware/lib/middleware.js:98:19)
    at ready (/app/node_modules/webpack-dev-middleware/lib/util.js:53:12)
    at handleRequest (/app/node_modules/webpack-dev-middleware/lib/util.js:182:5)
    at /app/node_modules/webpack-dev-middleware/lib/middleware.js:64:7
    at new Promise (<anonymous>)
    at middleware (/app/node_modules/webpack-dev-middleware/lib/middleware.js:63:12)
    at /app/node_modules/@angular-devkit/build-angular/src/webpack/plugins/karma.js:288:13
    at call (/app/node_modules/connect/index.js:239:7)
    at next (/app/node_modules/connect/index.js:183:5)
    at /app/node_modules/karma/lib/web-server.js:24:9
    at call (/app/node_modules/connect/index.js:239:7)
    at next (/app/node_modules/connect/index.js:183:5)
    at nullProxy (/app/node_modules/karma/lib/middleware/proxy.js:81:52)
    at call (/app/node_modules/connect/index.js:239:7)
    at next (/app/node_modules/connect/index.js:183:5)

If you read more carefully though you get an idea it has something to do with karma test runner and webpack code bundler. These two packages are included in Angular distribution and are used when running ng test.

The root cause of this issue might be some resource files you reference from assets folder. For instance the code as follows in one of your components would be sufficient for a random tests failure in Docker container:

<img src="../../../assets/welcome.jpg" title="Welcome" alt="Welcome" />

When executing tests through karma test runner the image is being loaded. Karma server should be configured appropriately so that it “knows” where to get the resource file from.

How To Fix It

If that’s your case a simple rule in karma.conf.js is sufficient for it. Simply add the following code after 

proxies: {
    '/assets/': '/base/src/assets/'

What it does is basically pointing all requests matching /assets/ pattern into the base foder of the project into src/assets/ folder. If the location of assets in your case is different, please adjust accordingly.

I hope that was helpful in building something great.

Take care,