簡體   English   中英

笑話單元測試 - 異步 function 中異步 function 的模擬值

[英]Jest unit test - mock value of async function within async function

在我的 React 項目中,我正在對調用另一個異步 function 的異步 function 進行單元測試。

//SomeComponent.js
getAllJobs = async () => {
    var allJobStatuses = new Array();
    for(var endpointForRegion in this.props.regionalEndpointsMap) {
        let jobStatusesForRegion = await getJobStatuses(endpoint);
        allJobStatuses = allJobStatuses.concat(jobStatusesForRegion);
....
    }
    return allJobStatuses;
}

getJobStatuses = async (endpoint) => {
   const response = await fetch(endpoint, {
   ......
   return await response.json();
}
//SomeComponentTest.js
describe('<SomeComponent />', () => {
    ....
    beforeEach(() => {
        props = {regionalEndpointsMap: {
             'region1': 'region1ep',
             'region2': 'region2ep'
        }};
        wrapper = shallow(<SomeComponent {...props} />);
    });
    it('should get jobs for all regions', async () => {
        var startTime = new Date();
        let mockdata = {[
            {
            jobId: 'id',
            }
        ]};

        jest.spyOn(wrapper.instance(), 'getJobStatuses').mockResolvedValue(data);
        let allJobs = wrapper.instance.getAllJobs();
        let expectedData = [
            {jobId:'id'},
            {jobId:'id'}
        ];
        expect(allJobs).toEqual(expectedData);
}

盡管每次對其進行測試,結果最終只是一個空的 Promise {} 而不是預期的數據。 我已經嘗試了許多我在網上找到的實現了ZD1892D85020BA222807BD0D8378206CC1Z async“ getJobStatuses'ZC425268E6838551AB5074C174C17A94F14S8的結果,在這里使用了ZC425268E68385D11AB5111AB8的實現(在這里顯示了ZC18的范圍8)。測試 function 調用它的目的 (getAllJobs)

由於getAllJobsasync的,它將返回 promise。 您的意思是在這里await promise 嗎?

let allJobs = await wrapper.instance.getAllJobs();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM