2016-09-26 5 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} 
} 

をし、私はこのようにそれを呼び出す:createClub()は角コントローラから呼び出され

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 
} 

。私はまだテストを続けているので、コントローラを書いているわけではありません。私はこのように、偽の応答に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ためcreateClubリターン約束は約束を返す必要があり、それはしていません?。おそらくまだ解決されていないでしょう。 – madflow

+0

はい。しかし、私がconsole.logを 'then'の中に入れば解決されるでしょう...そうですか?私はそれを試みた。 – Rodders

+0

あなたが作成しようとしている約束を解決するには、テストケースにスコープ/(rootscope)を注入し、スコープで次のダイジェストサイクルをキックする必要があります。$ digest() –

答えて

0

となることを期待しています。 $httpリクエストはすぐに解決されません。 (すなわちexistingClubundefinedとなり、validateClubは常に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) 
    }) 
} 

dataService.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) 
    } 
    // ... 

    }) 
} 
関連する問題