我正试图在我的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)
});
});
答案 0 :(得分:1)
其实我在这里看到拼写错误,或者代码可能不完整:
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)
});
});
答案 1 :(得分:0)
Alexander编写的代码是正确的,除了一个注释。您需要将间谍传递给Account构造函数。您传递给transaction
的名称jasmine.createSpyObj
只是一个将在错误消息中使用的名称。你可以省略它(在这种情况下它将是unknown
)
beforeEach(function() {
var transactionSpy = jasmine.createSpyObj('transaction',['returnBalance','withdraw','deposit']);
account = new Account(transactionSpy, statement)
});