問題
Sinon.JS v1.17.3 で発生する。
// before
const apiKey = 'xxx'; // ダミーの値
const sandbox = sinon.sandbox.create();
sandbox.stub(process.env, 'API_KEY', apiKey); // 存在しない環境変数 API_KEY (`process.env.API_KEY`) を apiKey で stub したい
//=> TypeError: Cannot stub non-existent own property API_KEY
// after
sandbox.restore(); // 元に戻す
解決策
ひとまず強引に null
を代入して回避した。この方法だと null
が戻されてしまうため、厳密には誤りがある。delete
するほうが良いが、実害はないので、この方法で対応している。
// before
const apiKey = 'xxx'; // ダミーの値
const sandbox = sinon.sandbox.create();
if (!process.env.hasOwnProperty('API_KEY')) process.env.API_KEY = null; // この行を追加し、強引に対応。
sandbox.stub(process.env, 'API_KEY', apiKey);
// after
sandbox.restore(); // 元に戻す
Sinon.JS での実装については source code を参照。
補足
個人的には勝手に追加して delete
してくれると嬉しいので、Pull Request してみたい。