pavlos163
pavlos163

Reputation: 2890

Jasmine spec fails

I am implementing my first web app (just following the AngularJS tutorial) using AngularJS and I am writing some tests using Jasmine and Karma.

This is my app.spec.js file:

describe('PhoneListController', function() {

  beforeEach(module('phonecatApp'));

  it('should create a `phones` model with 3 phones', inject(function($controller) {
    var scope = {};
    var ctrl = $controller('PhoneListController', {$scope: scope});

    expect(scope.phones.length).toBe(3);
    expect(scope.name).toBe('world');
  }));

});

Which works correctly. However, when I change it to:

describe('PhoneListController', function() {

  beforeEach(module('phonecatApp'));

  it('should create a `phones` model with 3 phones', inject(function($controller) {
    var scope = {};
    var ctrl = $controller('PhoneListController', {$scope: scope});

    expect(scope.phones.length).toBe(3);
  }));

  it('should have world as a name', inject(function($controller) {
    expect(scope.name).toBe('world');
  }));

});

What is wrong with the second approach? I thought that, roughly, each it statement corresponds to one test case and each describe statement corresponds to one test suite. Is that wrong?

Thanks.

Upvotes: 0

Views: 36

Answers (1)

Evan Trimboli
Evan Trimboli

Reputation: 30092

The it blocks are not executed as if they are a continuation. Also, the scope variable is local to the first test.

If we break it down, the second example is doing roughly:

function test1() {
    module('phonecatApp');
    var scope = {};
    var ctrl = $controller('PhoneListController', {$scope: scope});

    expect(scope.phones.length).toBe(3);
}

function test2() {
    module('phonecatApp');
    expect(scope.name).toBe('world');
}

test1();
test2();

You can see that in the second test, there's no scope or controller variable available.

Upvotes: 1

Related Questions