I’m trying to start unit testing (not using any testing frameworks) for my javascripts.
Here’s one example of it.
var obj = {};
obj.disableBtn = function ($btn, style) {
$btn.attr('disabled','disabled').addClass('disabled').removeClass(style);
};
The use case is as such:
obj.disableBtn($('.submit'), 'btn-blue');
What it does is simply add the disabled
attribute, add the disabled
class, and remove the btn-blue
style.
Please advise how would a typical test case look like in this case.
I have a little knowledge on testing using assert()
, but have no idea how to go about it when it involves verifying the result on HTML elements.
4
I appreciate that you do assert()’s. They’re simple and powerful, and non-magical.
You can test anything that is readable by code. Think “if I can if
this, then I can assert
it”.
If you want to write a test for something that updates markup, then the question is ‘how can I with code get the information I want to test?’.
If you’re using jQuery (it seems so) then have you test get the button with the selector $('.myButton')
. How would you write and if
to check the property of this button? I think you can do that. Then use the same code in your assert
. You’re closer than you think, you can do it!
I recommend using a JS unit testing framework, such as qUnit. There’s no need to reinvent unit testing tools from scratch, and you will be able to focus on testing your specific functionality.
You could then create a unit test that creates a button which is not disabled and has the “active” style properties attached to it. Next, run your disableBtn
function and assert that the button is disabled and no longer has the style attached to it. The unit test code would then look something like:
ok(true === yourButton.prop("disabled"));
ok(false === yourButton.hasClass('btn-blue'));
(jQuery functions used here since we’re mostly concerned about the unit testing code. You can of course check the attributes using vanilla JS).
1