繁体   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