テストのために即時関数の内部関数を輸出する
概要
html内の即時関数をどのようにテストするか考え、uni2vec開発中に適用しました。
- 即時関数実行の最後で、テストしたい関数をオブジェクトに詰めて返します(例ではexports for test)。
- 即時関数実行の返却値を変数に設定します(例ではmypackage)。
- テスト用htmlで対象htmlを内部フレームで読み込みます。
- テスト用htmlで対象フレームの輸出された変数を読み込み、実体に詰め込まれた関数を取り出します(例では
onst mypackage = window.frames[0].mypackage;
)。 - リリース時は輸出オブジェクトを返さないようにするか、変数への設定をやめます。
例
target.html
<!DOCTYPE html>
<html>
<head>
<script defer="defer">
;mypackage=(function(){
"use strict";
function plus(a, b) {
return a + b;
}
function PlusManager(a) {
this.a = a;
}
PlusManager.prototype.plus = function(b) {
return plus(this.a, b);
};
// exports for test
return {
plus:plus,
PlusManager:PlusManager,
};
})();
</script>
</head>
<body>
</body>
</html>
targettest.html
<!DOCTYPE html>
<html>
<head>
<script defer="defer">
;(function(){
"use strict";
function assertEquals(actual, expected) {
const a = JSON.stringify(actual);
const e = JSON.stringify(expected);
console.assert(a === e, '\nact: ' + a + '\nexp: ' + e);
}
window.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
const mypackage = window.frames[0].mypackage;
assertEquals(mypackage.plus(1, 2), 3);
const plusManager = new mypackage.PlusManager(1);
assertEquals(plusManager.plus(2), 3);
console.log("done");
}, 3000);
}, false);
})();
</script>
</head>
<body>
<iframe src="target.html" width="100" height="100"></iframe>
</body>
</html>