2017-08-13 25 views
0

功能的功能:玩笑單元測試調用如果我有代碼這樣的事情,它返回一個承諾

import externalThing from 'externalThing' 
import anotherThing from 'anotherThing' 

function functionIWantToTest() 
{  
    externalThing.doSomething() 
    .then(data=>{ 
     anotherThing.do(data.Id) 
    }) 
} 

什麼是最好的實踐方式,這個單元測試?

理想的測試將是這樣的:

import externalThing from 'externalThing' 
import anotherThing from 'anotherThing' 

jest.mock('externalThing',()=>jest.fn()) 
jest.mock('anotherThing',()=>jest.fn()) 

describe('when calling functionIWantToTest',()=>{ 

    beforeEach(()=>{  
     anotherThing.do=jest.fn() 
     //mock external thing somehow so that it still the 'then' code 

     functionIWantToTest() 
    }) 

    it('anotherThing should be called',()=>{ 
     expect(anotherThing.do).toHaveBeenCalledWith(1) 
    }); 
}); 

但是當我嘗試我剛剛結束了建築嘲笑功能鏈jest.fn(),並沒有實際的代碼被執行。

+0

什麼是預期的結果'functionIWantToTest()'調用? – guest271314

+0

嗨@ guest271314它在測試中:),用於'anotherThing.do'已用param調用。 – Dan

+0

還沒有嘗試'笑話'。 'jest.fn()'返回什麼? 「anotherThing.do」有兩種不同的賦值方式嗎?注意,沒有實際返回的值來自'functionIWantToTest()'調用 – guest271314

回答

1

還沒有試過jest。您可以使用console.assert()來測試返回的函數調用和Promise值。請注意,任何函數調用實際上都不會返回任何值,如果這一點與預期結果相關,請參閱Why is value undefined at .then() chained to Promise?

function functionIWantToTest() { 
 
    return Promise.resolve({ 
 
     Id: 1 
 
    }) 
 
    .then(data => { 
 
     console.assert(data.Id === 1, data, [`${data.Id} is not equal to 1`]); 
 
     console.assert(data.Id !== 1, data, [`${data.Id} is equal to 1`]); 
 
    }) 
 
} 
 

 
functionIWantToTest()

相關問題