2017-02-23 109 views
0

我正在使用AngularJS實現我的第一個Web應用程序(只是遵循AngularJS教程),我正在使用Jasmine和Karma編寫一些測試。茉莉花規格失敗

這是我app.spec.js文件:

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'); 
    })); 

}); 

哪個正常工作。但是,當我將其更改爲:

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'); 
    })); 

}); 

第二種方法有什麼問題?我認爲,大致上,每個it聲明對應於一個測試用例,並且每個describe聲明對應於一個測試用例。那是錯的嗎?

謝謝。

+2

簡單; 'scope'在你的第二個'it'函數中沒有定義。它只在第一次被定義 – Phil

回答

1

它阻止不執行,就好像它們是一個延續。另外,scope變量對第一個測試是本地的。

如果我們打破它,第二個例子是大致這樣做的:

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(); 

你可以看到,在第二次測試,有沒有可用的範圍或控制的變量。