0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Sinon.JS で存在しない環境変数を stub すると Error になる

Last updated at Posted at 2016-03-10

問題

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 してみたい。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?