要测试它frm.submit()
,你必须模拟它。有两种方法。第一种方法可以通过监视而无需更改代码,这将在您的示例中起作用,因为您只使用一次,如果更频繁document.getElementById
地使用它会更难。document.getElementById
var submit;
beforeEach(){
// when your code calls document.getElementById it return an object
// with just one property where you can spy on that it was called
submit = jasmine.createSpy();
spyOn(document 'getElementById').andReturn({submit:submit})
}
it ("should submit", function(){
submitform([somedata]);
expect(submit).toHaveBeenCalled();
})
更好的方法是重写代码以获得更好的可测试性。因此,不要通过调用 DOM 函数来获取表单,而是将表单作为参数注入到您的函数中。现在您可以将 mock 传递给您的函数而不是 mocking document.getElementById
。这种模式也称为依赖注入
function submitform(array, frm) {
var token = array[0].replace("access_token=", "");
if ((token !== "")) {
$('input[name=Token]').val(token);
frm.submit();
}
}
it ("should submit", function(){
var submit = jasmine.createSpy();
var form = {submit: submit}
submitform([somedata],form);
expect(submit).toHaveBeenCalled();
})