0

Consider the following snippet of my javascript function -

firstJs.prototype.SetSum=function(a,b){
    var htmlToBind="<div>"+(a+b)+"</div>";
    $('#setSum').html(htmlToBind);
};

Here setSum is a elementID in DOM.I would like to understand how will this function pass the unit testing done by Jasmine or Jest as and when the unit testing would run it will not find the 'setSum' in DOM hence fail the test case.I am a rookie in test cases

2 Answers 2

1

Techniques like dependency injection will help you here.

Instead of assuming that the element corresponding to $('#setSum') will be available to the function, pass the element in as a parameter.

For example, convert your function to this:

function (a, b, element) {
    var htmlToBind = "<div>" + (a + b) + "</div>";
    element.innerHTML(htmlToBind);
}

Now, your test function can pass in any HTML element to the third parameter.

Sign up to request clarification or add additional context in comments.

Comments

0

You can create an element with id setSum and append to the DOM.Use jasmine-jquery which proved a set of methods which can be used as a matcher.

Hopefully this snippet will be useful

 describe('Your test description',function(){
    //rest of the code
    // appending an element to the DOM, the original function will append
    // the new div inside this element
   $('body').append('<div id = "setSum"></div>');
   it('Should test element is bind to DOM',function(){
       firstJS.SetSum(4,5);
       expect($('#setSum')).toContainHtml('<div>9</div>');
       // remove the element after test

     }}
})

If you intend to fail it then skip $('body').append('<div id = "setSum"></div>');. The test will not find the DOM and will not able to use html method on it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.