用于动态字符计数的Jasmineunit testing用例

任何人都可以给我编写测试用例的示例,以检查是否在jquery和jasmine中调用了keyup事件中的函数。 我对jquery和jasmine相当新,所以很抱歉这些错误。 当用户输入输入字段中的字符时,此程序显示剩余的字符数。我遇到了我尝试过的测试用例如下

fixture.html :这是夹具

    

script.js :这是包含计算剩余字符的代码的脚本文件

 $(document).ready(function () { var txt = $('#text'); var remainingChar = $('#count'); var maxLengthBox = txt.attr('maxLength'); remainingChar.html(maxLengthBox); txt.keyup(function () { updateChars(remainingChar, maxLengthBox, txt) }); }); function updateChars(remainingChar, maxLengthBox, txt) { var remChar = maxLengthBox - $(txt).val().length; if (remChar < 0) { remChar = 0; } remainingChar.html(remChar); return remChar; } 

这是其中一个测试用例请在这里帮助我,因为它在触发keyup后没有调用该函数我该怎么测试它
1.如果函数updateChars(remainingChar,maxLengthBox,txt)被调用并执行
2.如何检查正确的remainingChar计数是否返回

TestCase从这里开始:
代码工作正常,但我需要帮助编写测试用例“检查是否显示正确的字符数”,因为触发updateCharsfunction在测试用例中没有为我调用内部updateChars函数

 beforeEach(function () { loadFixtures('Fixture.html'); txt = $('#text'); remainingChar = $('#count'); maxLengthBox = txt.attr('maxLength'); remainingChar.html(maxLengthBox); }); it("checking remaining characters", function () { txt.val('hello'); //entering hello into that text field //triggering keyup and expecting this to call the updateChars function txt.trigger('keyup'); expect(updateChars).toHaveBeenCalled(): }); 

好的,我假设您正在浏览器中直接运行测试,对吗? 通过您的代码,我假设updateChars函数是全局的,因此它附加到window

说,你需要的是spy ,在jasmine我们使用spyOn函数,这是一个例子:

 beforeEach(function() { //here we setup the "spy" spyOn(window, 'updateChars'); }); it("checking remaining characters", function() { txt.val('hello'); txt.trigger('keyup'); expect(updateChars).toHaveBeenCalled(): }); 

这只是一个需要根据您的需求进行调整的说明性示例。

一些笔记
我在你的代码中看到这行loadFixtures('Fixture.html'); ,我不知道它实际上是做什么的,但如果是异步调用,那么你需要在beforeEach使用done回调。

异步调用的另一个说明性示例:

 beforeEach(function(done) { //here we setup the "spy" spyOn(window, 'updateChars'); //supose this is a promise and we can call .then loadFixtures('Fixture.html') .then(function(){ txt = $('#text'); remainingChar = $('#count'); maxLengthBox = txt.attr('maxLength'); remainingChar.html(maxLengthBox); done(); //finally }); }); it("checking remaining characters", function(done) { txt.val('hello'); txt.trigger('keyup'); expect(updateChars).toHaveBeenCalled(): done(); }); 

希望能帮助到你