Kayvar Kayvar - 4 years ago 165
Javascript Question

How to use spyOn to mock jQuery value for a selector in Jasmine?

I'm writing some unit tests using AngularJS / Karma / Jasmine and couldn't get Jasmine's 'spyOn' method to work. After I use

, I'm still getting
for that selector.

The problem

The issue I'm running into, is after I run

spyOn($("#username"), "val").and.returnValue("test@test.com");

I try to get the value of username like this:


and it is

Code I want to 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 be true for valid emails', function() {
spyOn($("#username"), "val").and.returnValue("test@test.com");
var result = isValidEmail();


Anyone see anything I did wrong?

Answer Source

Your problem is that each time you call $("#username"), you get a different object. Therefore, the $("#username") in the function will not be spied on.

You should instead spy on $.fn, which will be shared by all jQuery objects.

spyOn($.fn, 'val').and.returnValue('test@test.com')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download