Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65871322/how-can-i-unit-test-my-javascript-code-in-a-way-that-allows-it-to-be-used-in-a-w

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...