2017-07-18 116 views
2

我試圖使用Jest測試(特別是AWS的Lambda),但我有困難異步等待功能。Jest - 試圖模擬異步等待在節點Js測試

我在用babel-jest和jest-cli。以下是我的模塊。 我正在訪問第一個console.log,但第二個console.log返回未定義的和我的測試崩潰。

關於如何實現這個的任何想法?

下面是我的模塊:

import {callAnotherFunction} from '../../../utils'; 

    export const handler = async (event, context, callback) => { 

    const {emailAddress, emailType} = event.body; 
    console.log("**** GETTING HERE = 1") 
    const sub = await callAnotherFunction(emailAddress, emailType); 
    console.log("**** Not GETTING HERE = 2", sub) // **returns undefined** 

    // do something else here 
    callback(null, {success: true, returnValue: sub}) 

} 

我的測試

import testData from '../data.js'; 
import { handler } from '../src/index.js'; 
jest.mock('../../../utils'); 

beforeAll(() => { 
    const callAnotherLambdaFunction= jest.fn().mockReturnValue(Promise.resolve({success: true})); 
}); 

describe('>>> SEND EMAIL LAMBDA',() => { 
    test('returns a good value', done => { 
    function callback(dataTest123) { 
     expect(dataTest123).toBe({success: true, returnValue: sub); 
     done(); 
    } 

    handler(testData, null, callback); 
    },10000); 
}) 

回答

0

jest.mock('../../../utils');是好的,但你實際上並沒有嘲諷的實施,你必須自己實施的行爲。

所以你需要添加

import { callAnotherFunction } from '../../../utils'; 

callAnotherFunction.mockImplementation(() => Promise.resolve('someValue')); 

test('test' , done => { 
    const testData = { 
    body: { 
     emailAddress: 'email', 
     emailType: 'type 
    } 
    }; 

    function callback(dataTest123) { 
    expect(dataTest123).toBe({success: true, returnValue: 'someValue'); 
    done(); 
    } 

    handler(testData, null, callback); 
}); 

希望這有助於。

+0

感謝您的及時迴應。我試過,得到以下錯誤:測試套件無法運行。 TypeError:_callAnotherLambdaFunction2.default.mockImplementation不是函數 – andre

+0

你的函數應該是'callAnotherFunction',因爲這是你試圖模擬的函數。不確定'callAnotherLambdaFunction'是什麼,我沒有在實際文件中看到 – grgmo

+0

是的,這是我在這個煮沸的例子中的一個錯字。在真正的測試中,這個函數無處不在 – andre

相關問題