Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9116249
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T04:37:37+00:00 2026-06-17T04:37:37+00:00

I have code in a JS file that like this (simplified of course): $(function

  • 0

I have code in a JS file that like this (simplified of course):

$(function () {
  var num;
  $.getJSON('./getNumber.php', function (n) {
    num = n;
  });

  $('#id').on('click', function () { alert(num); });
});

I need to write two unit tests:

  1. Make sure the script sends a ./getNumber.php request to server when page loads
  2. Make sure when #id is clicked, the num gets alerted.

Obviously I need FakeXmlHTTPRequest and mock the alert function, maybe even spy the $.getJSON. However I am not sure what’s the right way to write the tests while keeping the two atomic.

I think the only to doing so would dynamic inject the <script> block for each test; but I just feel that’s not right. What’s the right way? Thanks.

Edit: based on the comments outside of SO, what I need to learn is to write testable Javascript, instead of trying to come up test cases for something with low testabililty. If anyone can give me some advice on rewriting this code it will be also greatly appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T04:37:39+00:00Added an answer on June 17, 2026 at 4:37 am

    There isn’t one right answer to your question, but rather a lot of good principles to learn from. Consider the following code. I’ve refactored your example. I’ll explain everything I did below.

    // Define your module in a self-executing function.
    // This module is now completely unit testable.
    var myModule = (function () {
        var num;
    
        function getNum() {
            $.getJSON('./getNumber.php', function (n) {
                num = n;
            });
        }
    
        function alertNum() {
            alert(num);
        }
    
        // this returned object will by set to myModule and will publicly
        // expose the necessary functions
        return {
            getNum: getNum,
            alertNum: alertNum
        };
    })();
    
    // wire up your events
    $(function() {
        $("#id").on('click', myModule.alertNum);
    });
    

    This example is obviously overkill for this simple code, but it should give you some good ideas.

    1. Your core functionality is now encapsulated in a module. You keep additional private functions and variables inside the module (like num), but everything publicly exposed through the returned object can now be tested. (See Note below)

    2. I’ve wired up the events outside the module. If your module is large, you may even want to put this code in another script. Either way, it separates your concerns in a more MVC-like approach. You can test this chunk of code, but you shouldn’t really have to; it should be very straightforward jQuery, and wrapping tests around it would be little more than testing the jQuery library, which has already been thoroughly tested by the jQuery team.

    3. This may seem weird, but don’t use any jQuery selectors inside your module! If your module needs an element, pass it in as a function parameter. There are ways to stub that stuff out, but it’s really a hassle, and shouldn’t be necessary if you’ve properly separated your concerns. Most of my modules (or the objects in them) wind up with an init() method where I can pass in stuff. — You might still choose to use jQuery’s .find() method on your elements inside your module. That’s more a judgement call only you can make based on your module’s particular needs. Doing so will require you to do more detailed mocks of DOM elements in your tests, but sometimes it’s just easier than passing in dozens of elements into init() (just pass in the main container instead).


    Note: I strongly recommend using RequireJS or another AMD module loader for managing your modules. This will keep things like myModule above out of the global namespace. Setting up Require with QUnit is a little persnickety, though, and might be a problem to tackle later once you get a handle on unit testing.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a code that looks like this: int main () { fstream file;
I have a simple assembly code file called exit.s that looks like the following:
I have some setup code in my functions.php file that sets permalinks and adds
I have create a vcf file that contains contacts by using this code ContentResolver
I have this code that reads from XML file. It gets five strings (groupId,
I have a class with a few simple structs like this (simplified code) inside
I have a Xaml file that does not have any code behind. I would
In my application i need to open pdf file.For that i have prepared code
I have a simple java code that reads text csv file that contains sentences
I have a large JSON file that contains A LOT of similar code. It's

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.