属性 值在实例化后返回未定义

property values returning undefined after instantiation

这是一个使用 mocha 探索 TDD 的简单应用。该应用程序将获得两套扑克手牌并定义获胜手牌。

我在弄清楚为什么在对对象调用函数后我的值返回未定义时遇到了一些问题。实例化后,各个变量正确存储;但是使用函数检索那些较早值的变量 returns 它们未定义。一般来说,我是 node/web 开发的新手,我唯一能想到的可能是 sync/async?

代码可以在 github here

上找到

这里是终端:

images/undefined/undefined.img
{"suit":9,"val":1,"img":"images/undefined/undefined.img"}


  Test card module
    ✓ card is not null
    ✓ has all arguments valid and present
    ✓ has image value property
    1) has valid image path

  3 passing (13ms)
  1 failing

  1) Test card module has valid image path:
     AssertionError: expected [Function] to equal 'images/s/1.img'
      at Context.<anonymous> (test/cardTest.js:35:36)

下面是测试文件:

'use strict'

const app = require('express'),
      mocha = require('mocha'),
      chai = require('chai')

let expect = chai.expect

let card = require('../app/card.js')

describe('Test card module', () => {

  const myCard = new card.card('s', 1)
  console.log(JSON.stringify(myCard))

  it('card is not null', () => {

    expect(myCard).is.not.null
  })

  it('has all arguments valid and present', () => {

    expect(myCard).has.property('suit')
    expect(myCard).has.property('val')
  })


  it('has image value property', () => {

    expect(myCard).has.property('getCardImage')
  })

  it('has valid image path', () => {

    expect(myCard.getCardImage).to.equal('images/s/1.img')
  })


})

最后是应用程序文件:

'use strict'

function card(suit, val) {

  this.suit = suit
  this.val = val
  this.img = this.getCardImage()
}

card.prototype.getCardImage = () => {

  console.log('images/' + this.suit + '/' + this.val + '.img')
  let location = 'images/' + this.suit + '/' + this.val + '.img'

  return location
}

exports.card = card;

如有任何解释,我们将不胜感激;谢谢!

您需要调用函数

expect(myCard.getCardImage()).to.equal('images/s/1.img')

你应该使用普通函数,因为你有动态上下文this

card.prototype.getCardImage = function() {

  console.log('images/' + this.suit + '/' + this.val + '.img')
  let location = 'images/' + this.suit + '/' + this.val + '.img'

  return location
}