2016-09-26 47 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) 
    } 
    // ... 

    }) 
}