我已经建立了一个 maven 项目来使用 jasmin-maven-plugin 来测试我的 javascript 代码。插件是这样设置的:
<plugin>
<groupId>com.github.searls</groupId>
<artifactId>jasmine-maven-plugin</artifactId>
<version>1.2.0.0</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<jsSrcDir>src/main/webapp/js</jsSrcDir>
<jsTestSrcDir>src/test/javascript</jsTestSrcDir>
<sourceIncludes>
<include>jquery-1.8.2.min.js</include>
<include>jquery-ui-1.8.13.custom.min.js</include>
<include>jquery.json-2.2.js</include>
<include>stylesheet.js</include>
<include>**/*.js</include>
</sourceIncludes>
</configuration>
</plugin>
我编写了一个使用 jQuery 进行事件处理的 javascript 方法。代码是这样的:
registerDragSurface: function ( element, onDrag ) {
// Wrap every drag surface registration in a closure
// to preserve the given set of arguments as local variables
(function($, element, dragdropsystem, onDrag) {
// Register a mousemove event on the drag surface
$(element).mousemove (function ( event ) {
// If the user is dragging
if (dragdropsystem.isDragging) {
// Call the onDrag method with
// the given element and event
onDrag (element, event);
}
});
// Register a mouseup event on the drag surface
$(element).mouseup (function ( event ) {
// If the user is dragging
if (dragdropsystem.isDragging) {
// Call the onDragEnded function
dragdropsystem.onDragEnded();
}
// We are not dragging anymore, and
// the left mousebutton has been released
dragdropsystem.isDragging = false;
dragdropsystem.isMouseDown = false;
});
})($, element, this, onDrag);
},
然后我写了一个茉莉花规范来测试这个功能。代码在这里:
describe("linkedforms.dragdrop", function() {
var dragdrop = linkedforms.dragdrop;
it("test that a drag surface can be registered and onDragCallback is called", function () {
var dragSurface = {};
var onDragCallback = jasmine.createSpy("onDragCallback");
dragdrop.registerDragSurface(dragSurface, onDragCallback);
dragdrop.isDragging = true;
jQuery(dragSurface).trigger("mousemove");
expect(onDragCallback).toHaveBeenCalled();
expect(dragdrop.isDragging).toBe(true);
jQuery(dragSurface).trigger("mouseup");
expect(dragdrop.isDragging).toBe(false);
});
});
我可以从命令行运行 mvn jasmine:bdd,然后访问
http://localhost:8234
运行测试。这很好用,我的所有规格都通过了。然后我尝试使用 mvn test 从 maven 运行测试,但随后它中断了。它说 :
* Expected spy onDragCallback to have been called.
* Passed.
* Expected true to be false.
这让我怀疑 jQuery 事件系统在从 mvn test 运行时无法正常工作,因此在 HtmlUnit 浏览器中运行。有人知道如何解决这个问题吗?