如果函数不返回值,Jasmine如何工作?

时间:2013-09-05 09:26:48

标签: javascript jquery tdd bdd jasmine

首先,我是测试驱动开发(TDD)和行为驱动开发(BDD)的新手,我很难相信这是开发网页的好方法,因为页面经常需要以快速的方式开发,如果你必须先开发测试代码就很难做到。

任何方式!

我写这个帖子的原因不是因为,我发现了什么,问题(但如果你有输入,我也会喜欢阅读它!)。我一直在阅读一些关于语法,它是如何工作的以及所有这些。我发现,如果我的函数没有返回值,那么这种方法很难实现。

比方说,我有一个点击事件触发函数,它只是改变输入的文本值:

$('input[type="text"]').click(function() {
    $(this).val('Oh, that tickles!');
});

茉莉如何处理这个?如下代码?:

describe('Input type text is clicked', function () {  
    it('changes text in the input field', function () {  
        expect($('input[type="text"]').val()).toEqual("Oh, that tickles!");  
    });  
});

这虽然是错误的,因为jQuery对象可以包含多个不包含该值的输入字段。有没有找到元素的方法(例如$(this)或类似的),或者我应该在茉莉花测试中放置一个点击处理程序?像这样:

describe('Input type text is clicked', function () {  
    it('changes text in the input field', function () {
        $('input[type="text"]').click(function() {
            expect($(this).val()).toEqual("Oh, that tickles!");
        }  
    });  
});

一些清晰度会很好:)

提前多多感谢!

/ J。

1 个答案:

答案 0 :(得分:3)

一种方法是确保在运行测试时只有一个文本输入字段。您可以使用jasmine-jquery创建一个包含输入字段的灯具:

describe('Input type text is clicked', function () {  
  beforeEach(function() {
    jasmine.getFixtures().set('<input type="text" />');
    bindClickEvent();
  });
  it('changes text in the input field', function () {
    $('input[type="text"]').click();
    expect($('input[type="text"]').val()).toEqual("Oh, that tickles!");  
  });  
});

您可能想要重构代码,以便测试Click事件是否单独处理点击处理程序本身:

var eventHandlers = {
  tickle: function() {
    $(this).val('Oh, that tickles!');
  }
};    
$('input[type="text"]').click(eventHandlers.tickle);

然后你会有两个测试:

describe('Input type text is clicked', function () {  
  beforeEach(function() {
    jasmine.getFixtures().set('<input type="text" />');
    spyOn(eventHandlers, 'tickle');
    bindClickEvent();
  });
  it('should tickle the field', function () {
    $('input[type="text"]').click();
    expect(eventHandler.tickle).toHaveBeenCalled();
  });  
});

describe('eventHandlers.tickle', function () {  
  it('should set the field value', function () {
    var input = $('<input type="text"/>');
    eventHandlers.tickle.call(input);
    expect(input.val()).toBe("Oh, that tickles!");
  });  
});