实例化后返回undefined的属性值

时间:2017-06-17 08:30:35

标签: node.js ecmascript-6 mocha undefined chai

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

我有一些问题,在我调用对象上的函数后,弄清楚为什么我的值返回未定义。实例化后,各个变量存储正确;但是使用函数检索那些早期值的变量将它们返回为undefined。我是一般的节点/网络开发新手,我唯一能想到的可能是同步/异步?

代码可以在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')
  })


})

最后是app文件:

'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;

任何解释都将受到高度赞赏;谢谢!

1 个答案:

答案 0 :(得分:0)

你需要调用函数

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
}