如何编写一个jasmine单元测试用例来测试angularjs中的事件处理程序 [英] How to write a jasmine unit test case to test the event handlers in angularjs

查看:137
本文介绍了如何编写一个jasmine单元测试用例来测试angularjs中的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个茉莉花单元测试用例来测试按钮的点击事件。我已经为模态弹出写了以下测试用例,请找到我的plnkr 这里。我有一个名为Add的按钮。如果用户单击该按钮,则会打开一个模态弹出窗口。所以我想编写一个测试用例来查找当用户单击添加按钮时是否显示模态。我该怎么做?
谢谢,
Varun Krishna。 P

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

推荐答案

首先,与所有单元测试一样,确保您没有将N个测试合并为一个 - 总是导致麻烦。

First of, as with all unit tests, make sure that you're not mixing N tests into one - that always causes trouble.

在你的情况下,测试可以分成2个测试:

In your case, the test can be split into 2 tests:


  1. 单击添加时是否调用了正确的函数?

  2. 该函数是否显示模型对话框?

  1. Is the correct function called when Add is clicked?
  2. 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

第二个测试意味着您现在调用新函数并检查DOM中是否存在模态弹出窗口。

The second test means now that you call the new function and check whether there now a modal popup in the DOM.

这篇关于如何编写一个jasmine单元测试用例来测试angularjs中的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆