2016-09-26 79 views
0

正確的結果我有一個函數:

function validateClub(club) { 
    //.. other validation 

    let existingClub 
    $http.get('/clubs/fetch/' + club.clubName).then(data => { 
    existingClub = data 
    }, err => { 
    $log.error(err) 
    }) 

    console.log(existingClub) 

    if(existingClub) return {result: false, reason: 'Club already exists. Choose another Club Name'} 

    return {result: true} 
} 

,我這樣稱呼它:

function createClub(club) { 
    let validationResult = validateClub(club) 
    console.log(validationResult) 
    if (validationResult.result === false) { 
    throw new Error('The Club you entered has failed validation reason: ' + validationResult.reason) 
    } 

    // .. create club logic 
} 

createClub()從一個角度控制器調用。由於我堅持測試,我還沒有寫控制器。我使用ngMocks $ httpBackend僞造的響應,這樣的:

describe.only('when creating a new club with an existing clubName',() => { 
    it('should throw exception',() => { 
    $httpBackend 
     .when('GET', '/clubs/fetch/ClubFoo') 
     .respond(200, {_id:'1', clubName: 'ClubFoo', owner: '[email protected]'}) 

    const newClub = { 
     clubName: 'ClubFoo', 
     owner: '[email protected]', 
    } 

    dataService.createClub(newClub).then(data => { 
     response = data 
    }) 

    $httpBackend.flush() 
    // expect(fn).to.throw('The Club Name you have entered already exists') 
    // ignore the expect for now, I have changed the code for Stack Overflow 
    }) 
}) 

console.log(existingClub)總是undefined console.log(validationResult)總是{result: true}

我在做什麼錯?我期待前者爲{_id:'1', clubName: 'ClubFoo', owner: '[email protected]'},後者爲{result: false, reason: 'Club already exists. Choose another Club Name'}

+0

$ http.get回報承諾返回一個承諾,不是嗎?它可能還沒有解決 - 當你做的小console.log。 – madflow

+0

是的。但是,如果我在'then'中執行了console.log,那麼它會被解決......對吧?我試過了。 – Rodders

+0

爲了解決您要創建的承諾,您必須在您的測試用例中注入一個範圍/或(rootscope)並使用範圍啓動下一個摘要循環。$ digest() –

回答

0

這是時間問題。您的$http請求不會立即解決。 (即existingClubundefinedvalidateClub總是return {result: true})。

function validateClub(club) { 
    let existingClub 

    // make fn return promise 
    return $http.get('/clubs/fetch/' + club.clubName).then(data => { 
    // update existingClub info when $http req resolved 
    existingClub = data 
    console.log(existingClub) 

    if(existingClub) return {result: false, reason: '...'} 
    return {result: true} 
    }, err => { 
    $log.error(err) 
    }) 
} 

也應該createClubdataService.createClub(newClub).then(...)

function createClub(club) { 
    return validateClub(club).then(validationResult => { 
    console.log(validationResult) 
    if (validationResult.result === false) { 
     throw new Error('The Club you entered has failed validation reason: ' + validationResult.reason) 
    } 
    // ... 

    }) 
}