问题
I am currently writing a jasmine unit test case to test the button's click event. I have written the following test cases for modal popup, please find my plnkr here. I have a button called Add. If the user clicks the button a modal popup opens. So I want to write a test case to find whether the modal is displayed when the user clicks the add button. How do I do it? Thanks, Varun Krishna. P
回答1:
First of, as with all unit tests, make sure that you're not mixing N tests into one - that always causes trouble.
In your case, the test can be split into 2 tests:
- Is the correct function called when
Add
is clicked? - Does the function display a model dialog?
For the first test, I suggest that you move the code for the event handler into a function instead of in-lining it. That way, you can overwrite the function in the test setup and restore it later (pseudo-code):
// setup
var origFunc = addFunction;
var iWasCalled = false;
addFunction = function() { iWasCalled = true; }
// test
$('#add').click();
// validation
assert that iWasCalled is now true
// tear down
addFunction = origFunc
The second test means now that you call the new function and check whether there now a modal popup in the DOM.
来源:https://stackoverflow.com/questions/21377684/how-to-write-a-jasmine-unit-test-case-to-test-the-event-handlers-in-angularjs