开发环境:Ruby on rails,jasmine。
需要测试的功能:获取点击坐标并使用x,y。
设置文本字段值$(document).on('ready page:load', function() {
$('.floor_map_edit').click(function(e) {
var posX = $(this).offset().left, posY = $(this).offset().top;
document.getElementById("location_x").value = (e.pageX - posX);
document.getElementById("location_y").value = (e.pageY - posY);
});
});
茉莉花中的测试功能:(试图添加灯具,我不知道我在做什么)
describe("Edit Locations", function() {
beforeEach(function() {
var posX,posY = null;
loadFixtures('floor_map_click.html');
nameFields = $(".name-field");
spyOn($('.floor_map_edit'), "click");
});
it("should asset x, y coordinate inside text fields", function() {
//$('.floor_map_edit').click();
$('.floor_map_edit').trigger('click');
expect($(document.getElementById("location_x")).value).toBeGreaterThan(0);
expect($(document.getElementById("location_x")).value).toBeGreaterThan(0);
});
});
夹具:
<div class="floor_map_edit"><p>Hello World</p></div>
<form>
<input type="text" id="location_x" data-id-field="id-field1" class="name-field">
<input type="text" id="location_y" data-id-field="id-field2" class="name-field">
</form>
PS:我对RoR和茉莉是全新的。我已经阅读了这些文件来解决这个问题。非常感谢任何帮助。
答案 0 :(得分:1)
首先,我们需要一个点击元素内部的小测试助手:
jQuery.fn.extend({
clickInside : function(x, y){
var offset = this.offset();
var e = new jQuery.Event("click");
e.pageX = offset.left + x;
e.pageY = offset.top + y;
return this.trigger(e); // for chaining
}
});
http://jsfiddle.net/maxcal/32z62kyv/
然后测试它就像触发点击一样简单,然后检查相应的输入是否具有正确的值。
但请记住,文本字段的值是一个字符串。这就是为什么检查.toBeGreaterThan
会失败。
describe("Edit Locations", function(){
beforeEach(function(){
loadFixtures('floor_map_click.html');
// Jasmine will automatically clean these up for us
this.nameFields = $(".name-field");
this.floor_map = $("floor_map_edit");
});
// one expectation per example is a good practice.
it("updates X coordinate when I click map", function(){
this.floor_map.clickInside(6, 9);
// ensure that we are comparing an number and not a string
expect( parseInt($("#location_x").val()) ).toEqual(6);
});
it("updates Y coordinate when I click map", function(){
this.floor_map.clickInside(6, 9);
expect( parseInt($("#location_y").val()) ).toEqual(9);
});
});