2017-07-18 4 views
2

ノードJsテスト(特にAWSのラムダ)にJestを使用しようとしていますが、非同期待機機能が苦労しています。Jest - ノードJsテストで非同期待機しようとしました

私はバベル・ジェストとjest-cliを使用しています。以下は私のモジュールです。 私は最初のconsole.logになっていますが、2番目の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

関連する問題