簡體   English   中英

如何正確使用茉莉花間諜來模擬交易

[英]How to correctly use Jasmine spies to mock transactions

我正在嘗試從我的account_spec中的事務模塊中模擬行為。 我發現很難。 一次,我從我的帳戶存款,我不得不模擬交易的行為,但是我發現這很困難。 我的測試當前返回的'Transaction' is not undefined

編輯:

我有一個帳戶模塊:

function Account(statement = new Statement, transaction = new Transaction){
  this._statement = statement
  this._transaction = transaction
}

Account.prototype.deposit = function(amount) {
  this._transaction.deposit(amount)
  this._statement.storeHistory(amount, this._balance, "Deposit")
}

Account.prototype.withdraw = function(amount) {
  this._transaction.withdraw(amount)
  this._statement.storeHistory(amount, this._balance, "Withdraw")
}

Account.prototype.balance = function() {
  return this._balance
}
module.exports = Account;

我有一個交易模塊:

function Transaction(){
    this._balance = 0
}

Transaction.prototype.balance = function() {
    return this.balance
}

Transaction.prototype.deposit = function(amount) {
    this._balance += amount
}

Transaction.prototype.withdraw = function(amount) {
    this._balance -= amount
}

module.exports = Transaction;

我的聲明:

function Statement(){
  this._logs = []
}

Statement.prototype.seeStatement = function() {
  return this._logs
}

Statement.prototype.storeHistory = function(amount, balance, type) {
  this._logs.push({amount: amount, balance: balance, type: type})
}

module.exports = Statement;

我的帳戶規格:

'use strict';

describe('Account',function(){
  var account;
  beforeEach(function(){
    statement = new Statement
    var transactionSpy = jasmine.createSpyObj('transaction',['balance','withdraw','deposit']);
    account = new Account(statement, transactionSpy);
  });
  it('is able for a user to deposit', function(){
    account.deposit(40)
    // expect(account.balance()).toEqual(40)
  });
  it('is able for a user to withdraw', function() {
    account.deposit(40)
    account.withdraw(20)
    // expect(account.balance()).toEqual(20)
  });
  it('is able for a user to check their balance', function() {
    account.deposit(20)
    expect(transaction.balance()).toEqual(20)
  });
});

其實我在這里看到錯字,或者代碼不完整:

describe('Account', function() {
  var account;
  var transaction;
var statement = {}; //or some mock object

  beforeEach(function() {
    var spy = jasmine.createSpyObj('transaction',['returnBalance','withdraw','deposit']);
    account = new Account(transaction, statement)
  });

  it("is able to deposit money", function() {
    account.deposit(40)
    expect(transaction.returnBalance).toEqual(40)
    });
});

亞歷山大寫的代碼是正確的,只有一個注釋。 您需要將間諜傳遞給Account構造函數。 您傳遞給jasmine.createSpyObj的名稱transaction只是將在錯誤消息中使用的名稱。 您可以忽略它(在這種情況下,它將是unknown

 beforeEach(function() { var transactionSpy = jasmine.createSpyObj('transaction',['returnBalance','withdraw','deposit']); account = new Account(transactionSpy, statement) }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM