【问题标题】:property values returning undefined after instantiation实例化后返回未定义的属性值
【发布时间】:2017-06-17 08:30:35
【问题描述】:

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

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

代码可以在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;

任何解释都将不胜感激;谢谢!

【问题讨论】:

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


    【解决方案1】:

    你需要调用函数

    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
    }
    

    【讨论】:

    • 嗯,答案比我预期的要简单得多。我还研究了箭头函数以及它们可能对“this”造成的问题。学到了很多,谢谢! derickbailey.com/2015/09/28/…
    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2020-11-10
    • 2012-06-15
    • 2022-08-20
    • 1970-01-01
    相关资源
    最近更新 更多