mardi 4 juin 2019

JavaScript unittesting with Jest - how do I run my scripts in the browser?

I use Jest to unittest my JavaScript code. Or at least I'd really want to use Jest.

The problem is that Jest need me to use module.exports in order to use the function inside of the testfile. And that means I can't use my JavaScript in the browser.

The simple Jest test looks like this:

// divide.js
function divide(a, b) {

  return a / b;

}

module.exports = divide;


// divide.test.js
const divide = require('./divide');

test('divides 10 by 2 equal to 5', () => {

  expect(divide(10, 2)).toBe(5);

});


And it works fine. I run test in the CLI and everything is nice.

I realize that Jest is written with React in mind (hence every guide on Jest uses React) but it seems to make a lot of sense for testing with (vanilla) JavaScript.

I realize that module.exports and require are Node.js specific. But I can't figure how to handle them in a way so that I can use the functions in my browserrendered code.3

Until now I've been solving this problem by commenting out module.exports - and that for sure ain't a viable way.

So my question is: How do I get to use my divide.js both in the test and in the browser?

I can think of to ways to go here: - Switch the testsuite to something else - Figure out what tooling or setup I need to create something like a main.js from the files containing module.exports in a way so that it can be used in the browser

Aucun commentaire:

Enregistrer un commentaire