javascript - How to use spyOn to mock jQuery value for a selector in Jasmine? -
this question has answer here:
- spying on jquery selectors in jasmine 6 answers
i'm writing unit tests using angularjs / karma / jasmine , couldn't jasmine's 'spyon' method work. after use spyon
, i'm still getting undefined
selector.
the problem
the issue i'm running into, after run
spyon($("#username"), "val").and.returnvalue("test@test.com");
i try value of username this:
$("#username").val();
and undefined
.
code want test
function isvalidemail() { var email = $("#username").val(); var regex = /^([a-za-z0-9_.+-])+\@(([a-za-z0-9-])+\.)+([a-za-z0-9]{2,4})+$/; return email.match(regex); }
unit test
'use strict'; describe('test/spec/controllers/validation.js - no controller', function () { describe('email validation', function () { it('should true valid emails', function() { spyon($("#username"), "val").and.returnvalue("test@test.com"); var result = isvalidemail(); expect(result).toequal(true); }); }); });
anyone see did wrong?
your problem each time call $("#username")
, different object. therefore, $("#username")
in function not spied on.
you should instead spy on $.fn
, shared jquery objects.
spyon($.fn, 'val').and.returnvalue('test@test.com')
Comments
Post a Comment