Aerus Aerus - 8 months ago 63
AngularJS Question

Jasmine test input with pattern

I have a form with the following input:

<input type="email" name="email" ng-model="" ng-pattern="emailRegex">

I want to test that the form is invalid if the user types an invalid email:

it('...', function() {$setViewValue('invalid');
expect($valid).toBeFalsy(); // OK$setViewValue('invalid@');
expect($valid).toBeFalsy(); // OK$setViewValue('invalid@host');
expect($valid).toBeFalsy(); // Not OK

The last expectatijon fails because the input is valid, although the email regex expects a domain. It feels as if the pattern is not used in my test because when I change the type to text, it already fails at the first expectation. How can I make sure the pattern is picked up in the tests?

For completeness, this is the regex (not written by me):


Changing the type to
didn't work.

I'm using jasmine 2.4.1 and angular 1.4.2. I'm using ngHtml2JsPreprocessor as explained here to initialize the form in my tests.


This is how to form is initialized:

beforeEach(inject(function($rootScope, $templateCache, $compile) {
var $scope = $rootScope.$new();
vm = $controller('RegisterController', {$scope: $scope});
var templateHtml = $templateCache.get("register.html");
var template = angular.element("<div>" + templateHtml + "</div>");
var form = $scope.registerForm;
scope = $scope;


AngularJS still works in the way, how it was developed

angular.module('app', [])

describe('Registration form', () => {
  'use strict'


  let form
  let scope

  beforeEach(inject(($rootScope, $compile) => {
    scope = $rootScope.$new()
    var formElem = ['<form name="registrationForm">',
      '<input type="text" name="number" ng-model="input" ng-pattern="/^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9]+[_A-Za-z0-9-]*[_A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$/">',
    form = scope.registrationForm

  it('has no `$valid` state', () => {
    form.number.$setViewValue('invalid email address')

  it('has `$valid` state', () => {
<script src=""></script>
<script src=""></script>
<script src=""></script>
<link href="" rel="stylesheet" />