[解決済み] Sinon.jsでクラスメソッドをスタブする
2022-09-24 11:07:03
質問
sinon.jsを使ってメソッドをスタブ化しようとしているのですが、以下のエラーが発生します。
Uncaught TypeError: Attempted to wrap undefined property sample_pressure as function
また、この質問にも行ってみました( sinon.jsでクラスのスタブやモッキングを行うことはできますか? ) にアクセスし、コードをコピーして貼り付けましたが、同じエラーが発生しました。
以下は私のコードです。
Sensor = (function() {
// A simple Sensor class
// Constructor
function Sensor(pressure) {
this.pressure = pressure;
}
Sensor.prototype.sample_pressure = function() {
return this.pressure;
};
return Sensor;
})();
// Doesn't work
var stub_sens = sinon.stub(Sensor, "sample_pressure").returns(0);
// Doesn't work
var stub_sens = sinon.stub(Sensor, "sample_pressure", function() {return 0});
// Never gets this far
console.log(stub_sens.sample_pressure());
以下は、jsFiddle( http://jsfiddle.net/pebreo/wyg5f/5/ )です。また、上記のコードのjsFiddleと、私が言及したSOの質問のjsFiddle( http://jsfiddle.net/pebreo/9mK5d/1/ ).
私は、シノンを必ず 外部リソース をjsFiddleで、さらにjQuery 1.9で確認しました。私は何か間違っているのでしょうか?
どのように解決するには?
あなたのコードでは、関数のスタブを
Sensor
にある関数をスタブしようとしていますが、あなたはその関数を
Sensor.prototype
.
sinon.stub(Sensor, "sample_pressure", function() {return 0})
は基本的にこれと同じです。
Sensor["sample_pressure"] = function() {return 0};
が、賢いので
Sensor["sample_pressure"]
は存在しないことを見抜きます。
ということで、やりたいことは以下のようなことです。
// Stub the prototype's function so that there is a spy on any new instance
// of Sensor that is created. Kind of overkill.
sinon.stub(Sensor.prototype, "sample_pressure").returns(0);
var sensor = new Sensor();
console.log(sensor.sample_pressure());
または
// Stub the function on a single instance of 'Sensor'.
var sensor = new Sensor();
sinon.stub(sensor, "sample_pressure").returns(0);
console.log(sensor.sample_pressure());
または
// Create a whole fake instance of 'Sensor' with none of the class's logic.
var sensor = sinon.createStubInstance(Sensor);
console.log(sensor.sample_pressure());
関連
-
[解決済み] jQueryでチェックボックスに "checked "を設定する
-
[解決済み] JavaScriptで現在のURLを取得する?
-
[解決済み] JavaScriptで要素のクラスを変更するにはどうすればよいですか?
-
[解決済み] jQueryでページを更新するにはどうすればよいですか?
-
[解決済み] jQueryで要素にスクロールする
-
[解決済み] jQueryで入力を無効化/有効化する?
-
[解決済み] forEachループでasync/awaitを使用する
-
[解決済み] React js 親コンポーネントから子コンポーネントの状態を変更する
-
[解決済み] JSXとLoadshを使用して、ある要素をn回繰り返す方法
-
[解決済み] JavaScriptでDIVを表示・非表示にするには?
最新
-
nginxです。[emerg] 0.0.0.0:80 への bind() に失敗しました (98: アドレスは既に使用中です)
-
htmlページでギリシャ文字を使うには
-
ピュアhtml+cssでの要素読み込み効果
-
純粋なhtml + cssで五輪を実現するサンプルコード
-
ナビゲーションバー・ドロップダウンメニューのHTML+CSSサンプルコード
-
タイピング効果を実現するピュアhtml+css
-
htmlの選択ボックスのプレースホルダー作成に関する質問
-
html css3 伸縮しない 画像表示効果
-
トップナビゲーションバーメニュー作成用HTML+CSS
-
html+css 実装 サイバーパンク風ボタン
おすすめ
-
[解決済み] JSのDateからDay名
-
[解決済み] AngularJSのエラーです。Cross Origin リクエストはプロトコルスキーム http, data, chrome-extension, https に対してのみサポートされています。
-
[解決済み] JavaScript で範囲を作成する - 奇妙な構文
-
[解決済み] JavaScriptでの大文字小文字を区別しない正規表現
-
[解決済み] jQueryの$という記号の意味は何ですか?
-
[解決済み] Javascriptで動的に命名されたメソッドを呼び出すにはどうすればよいですか?
-
[解決済み] モデルフェッチ時に1をtrueに、0をfalseに変換する方法
-
[解決済み] Prototypeを使ってtextareaを自動サイズ調整するには?
-
[解決済み] querySelectorAllがない場合、ライブラリを使用せずに属性で要素を取得する?
-
[解決済み] これは純関数ですか?