Jasmine中的鼠标事件

时间:2013-02-12 17:24:48

标签: jquery jasmine

我是Jasmine和jQuery的新手,我在监视mousedown事件时遇到了麻烦。这是我的规范失败的一部分(Jasmine说间谍mousedown没有被调用。)我怀疑这可能是因为我触发事件的方式。

it("draws a path on mousedown", function() {
  spyOn(drawing,'mousedown');
  $('#canvas').trigger('mousedown');
  expect(drawing.mousedown).toHaveBeenCalled();
  expect(drawing.isDrawing).toEqual(true);
});

相应的Javascript代码在这里:

function Drawing(canvas, eraseAllButton, eraseButton) {
  this.isDrawing = false;
  this.erasing = false;
  this.canvas = canvas;
  this.context = canvas.getContext("2d");
  this.eraseAllButton = eraseAllButton;
  this.eraseButton = eraseButton;

// Sets up event listeners for drawing.
  var self = this;
  this.canvas.addEventListener("mousedown", function () { self.mousedown() }, false);
};

// Begins to draw a path on mousedown.
Drawing.prototype.mousedown = function(e) { 
  if (!e) var e = window.event;
  e.preventDefault();       

  this.isDrawing = true;
  this.x = e.pageX - this.canvas.offsetLeft;
  this.y = e.pageY - this.canvas.offsetTop;
  this.context.beginPath();
  this.context.moveTo(this.x, this.y);
};

1 个答案:

答案 0 :(得分:0)

试试这个:

var mouse = document.createEvent('MouseEvents');
mouse.initMouseEvent('mousedown', true, true, window);
$('#canvas').get(0).dispatchEvent(mouse);