简体   繁体   中英

How can I unit test my JavaScript code in a way that allows it to be used in a website?

I have built a web app and I am trying to build out an automated unit testing suite so that I can more easily refactor the code.

I have javascript code that functions correctly on my website. Simple hypothetical code:

function timesTwo(x){x*=2;return x}

If I were writing my code for NodeJS I would add the tests to confirm that the code is working correctly. Below is an example using Wish and Mocha:

describe('timesTwo()', function() {
  it('multiplies by two', function() {
    var result = timesTwo(5);
    wish(result === 10);
  });
});

This code (including tests) works fine if I run it in node.JS to test it, but now it throws errors in my browser:

require is not defined

describe is not defined

wish is not defined

How can I create an automated test suite for my code in a way that doesn't throw errors in the browser?

If I'm not mistaken you're also loading the test code into your browser.

The thing is that require isn't something that's available in your browser. This means that the functions like describe and wish are simply not available since the require didn't include any code.

What you should do is keep the tests separate from your application code and only load the application code into your website. How you do this depends on your build system, template engine, etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM