2017-09-29 1 views
7

私はprocess.on('SIGTERM')コールバックでJestを使ってユニットテストをしようとしていますが、決して呼び出されないようです。私はjest.useFakeTimers()を使用していますが、setTimeoutのコールをモックしているように見えますが、チェックするとsetTimeout.mockオブジェクトには終わりません。NodeJS - JestユニットテストsetTimeout in process.onコールバック

マイindex.jsファイル:

process.on('SIGTERM',() => { 
    console.log('Got SIGTERM'); 

    setTimeout(() => { 
     console.log('Timer was run'); 
    }, 300); 
}); 

setTimeout(() => { 
    console.log('Timer 2 was run'); 
}, 30000); 

とテストファイル:

期待値があることを(使用して===):

describe('Test process SIGTERM handler',() => { 
    test.only('runs timeout',() => { 
     jest.useFakeTimers(); 
     process.exit = jest.fn(); 

     require('./index.js'); 

     process.kill(process.pid, 'SIGTERM'); 

     jest.runAllTimers(); 

     expect(setTimeout.mock.calls.length).toBe(2); 
    }); 
}); 

と、テストは失敗します:受信:とコンソールログ出力:

console.log tmp/index.js:10 
    Timer 2 was run 

    console.log tmp/index.js:2 
    Got SIGTERM 

にはどうすればsetTimeoutがここで実行することができますか?

+0

テストのためにSIGHUPするSIGTERMを変更してみてください。 sigtermがプロセスを終了させる可能性があります。また、タイマー1を削除し、コンソールログが実際に同期方式で動作しているかどうかを確認してください。 – Jehy

答えて

4

可能なことは、killメソッドでハンドラが呼び出されるようにプロセスonをモックすることです。

killと一緒にonをモックする方法があります。

describe('Test process SIGTERM handler',() => { 
    test.only('runs timeout',() => { 
     jest.useFakeTimers(); 

     processEvents = {}; 

     process.on = jest.fn((signal, cb) => { 
      processEvents[signal] = cb; 
     }); 

     process.kill = jest.fn((pid, signal) => { 
      processEvents[signal](); 
     }); 

     require('./index.js'); 

     process.kill(process.pid, 'SIGTERM'); 

     jest.runAllTimers(); 

     expect(setTimeout.mock.calls.length).toBe(2); 
    }); 
}); 

その他の方法で、一般の方は、setTimeout内のハンドラを模擬し、次のように呼ばれているされてテストすることです:

index.js

var handlers = require('./handlers'); 

process.on('SIGTERM',() => { 
    console.log('Got SIGTERM'); 
    setTimeout(handlers.someFunction, 300); 
}); 

handlers.js

module.exports = { 
    someFunction:() => {} 
}; 

index.spec.js

describe('Test process SIGTERM handler',() => { 
    test.only('sets someFunction as a SIGTERM handler',() => { 
     jest.useFakeTimers(); 

     process.on = jest.fn((signal, cb) => { 
      if (signal === 'SIGTERM') { 
       cb(); 
      } 
     }); 

     var handlerMock = jest.fn(); 

     jest.setMock('./handlers', { 
      someFunction: handlerMock 
     }); 

     require('./index'); 

     jest.runAllTimers(); 

     expect(handlerMock).toHaveBeenCalledTimes(1); 
    }); 
}); 
関連する問題