Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Jest error with Maximum Call Stack Size Exceeded When I Import KnockoutJS Into A ViewModel I'm Testing?

I'm trying to write some tests using Jest for a KnockoutJs Project.

Apologies for any terminology I get wrong below I'm coming back to JS after about 10 years of not using it and still getting my head round things like ES6 modules.

The tests work fine until I need to test a ViewModel that uses knockout observable objects, I've added an import to my viewmodel to bring in KnockoutJs using ES6 module syntax and have babel setup to compile this so it should work in node.

My viewmodel looks like this...

export { myVm }
import * as ko from 'knockout'

function myVm() {
    var self = this;

    self.helloWorld = function () { return "Hello World" }

    return self;
}

Then my test file looks like...

import * as vm from '../src/viewModels/myVm'

test('Returns Hello World', () => {
    expect(vm.myVm().helloWorld()).toBe('Hello World');
});

When I execute Jest I get a Maximum call stack size exceeded error

Error Screenshot

If I remove the import * as ko line from my ViewModel it works fine but then I can't reference any of the object types in the knockout library.

Not sure if it's relevant but my .babelrc looks like this...

{
    "presets": [
        "env"
    ]
}

Any idea what I'm doing wrong when I'm importing Knockout into the ViewModel?

Edit : This is my package.json

{
  "name": "blah",
  "version": "1.0.0",
  "description": "blah",
  "main": "index.js",
  "dependencies": {
    "knockout": "^3.5.1"
  },
  "devDependencies": {
    "babel-jest": "^24.9.0",
    "babel-preset-env": "^1.7.0",
    "jest": "^24.9.0"
  },
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC"
}
like image 744
Gavin Avatar asked Dec 04 '19 08:12

Gavin


1 Answers

You're using an older than Babel 7 version and it looks like it has issues when importing * as ko syntax.

You can either upgrade to Babel 7 and everything will work as you have it, or just change:

import * as ko from 'knockout'

to:

import ko from 'knockout'

Upgrating Babel

There are a lot of resources on how to upgrade Babel, but it's not hard. Instal latest Babel @babel/core and @babel/preset-env:

npm install -D @babel/core @babel/preset-env

// OR

yarn add @babel/core @babel/preset-env --dev

and then change the contents of .babelrc to have the new @babel/preset-env like this:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

You can omit the target, but you should always use it to minimize what polyfills are included:

{
  presets: ['@babel/preset-env']
}
like image 191
Christos Lytras Avatar answered Nov 10 '22 04:11

Christos Lytras