Coop Coop - 2 months ago 9
AngularJS Question

$provide more than 1 value to test in a describe

I have a Karma/Jasmine test for an Angular directive:

describe('placeholder directive', function() {

// Bindable members
var element;

// Load module
beforeEach(angular.mock.module('app'));

// Mock service response
beforeEach(module(function($provide) {
$provide.value('PlaceholderSupportService', function() {
return false;
});
}));

// Bind references to global variables
beforeEach(inject(function($compile, $rootScope) {
element = $compile('<input name="test" placeholder="Test" />')($rootScope);
$rootScope.$digest();
}));

// Check the correct HTML is rendered
it('Renders placeholder as input value when placeholder is not supported', inject(function($timeout) {
$timeout.flush();
expect(element[0].value).toBe('Test');
}));

});


It works as I want. However, I have forced the value of
PlaceholderSupportService()
to be
false
. I want to run a second test where I have this value as
true
. I can't seem to access
$provide
within an
it
statement, so how do I do this?

Answer

You could tell your PlaceholderSupportService to return a variable. And then, on your test block, you change the value of the variable. This should solve the problem. Here is the example:

describe('placeholder directive', function() {

  // Bindable members
  var element;
  var providerResult = false; //Here is the variable that you will change.

  // Load module
  beforeEach(angular.mock.module('app'));

  // Mock service response
  beforeEach(module(function($provide) {
    $provide.value('PlaceholderSupportService', function() {
      return providerResult;
    });
  }));

  // Check the correct HTML is rendered
  it('Renders placeholder as input value when placeholder is not supported', inject(function($timeout) {
    element = $compile('<input name="test" placeholder="Test" />')($rootScope);
    $rootScope.$digest();
    $timeout.flush();
    expect(element[0].value).toBe('Test');
  }));

  // Check the correct HTML is rendered
  it('Renders placeholder as input value when placeholder is supported', inject(function($timeout) {
    providerResult = true; //Here I will change the result of my PlaceholderSupportService
    element = $compile('<input name="test" placeholder="Test" />')($rootScope);
    $rootScope.$digest();
    $timeout.flush();
    expect(element[0].value).toBe('Test');
  }));

});
Comments