2016-11-24 30 views
0

試圖測試JavaScript對象如何測試一個Javascript對象屬性時摩卡功能,柴

Game.js

var GameManager= { 
    gameType: 'room', 
    roomDimension: [10,10], 
    playerDirection: ["W"] 
    possibleDirections: ["N","E","S","W"], 
    init: function(){ 
     if(this.gameType == 'room'){ 
      regexpNumber = /^-?[0-9]$|-?([1][0-9])$/; 
     } 
    return true; 
    }, 
    turnRight : function(){ 
    var movePosition = this.possibleDirections.indexOf(this.playerDirection); 
    if(movePosition == this.possibleDirections.length -1){ 
     return this.possibleDirections[0]; 
    } 
    return this.possibleDirections[movePosition + 1]; 
    }, 
    commandString: function(string){ 
    var command = /^[PQR]*$/; 

    if(command.test(string){ 
     return true; 
    } 
    this.errorMessageNumber = 0; 
    return false; 
} 
} 

這裏是我的測試腳本test.js

var expect = require("chai").expect; 
var GameManager = require("../GameManager.js"); 

describe("Test game type", function() { 
    beforeEach(function() { 
     GameManager.gameType = 'room'; 
     GameManager.roomDimension= [10, 10]; 
     GameManager.possibleDirections: ["N","E","S","W"]; 
    }); 

    it('should commandString be as parameters', function() { 
    expect(GameManager.commandString("AABB")).to.not.be.false; 
    }); 

    it('should init toBeTruthy', function() { 
    expect(GameManager.init()).ok; 
    }); 
}); 

問題:在兩種情況下,測試失敗,出現TypeError錯誤,如下所示,其中一個t他測試:

1) Test game type should init toBeTruthy: 
    TypeError: GameManager.init is not a function at Context.<anonymous> 

由於init在這裏不被認爲是功能,所以如何測試?

+0

測試的預期看起來不錯,也許'常量期待=需要('柴')期望;'你進口柴的方式。 – Hosar

+1

另外你是如何導出GameManager的? – Hosar

+0

@Hosar將代碼更改爲'var expect = require(「chai」)。expect;' 我不輸出GameManager,因爲它是一個簡單的Javascript對象。不使用「Typescript」導出類。 – shaz

回答

0

你爲什麼要測試一個簡單的對象? 我認爲,儘管可以做到,UT更多的是做行爲測試。

這麼說,我覺得你正在使用的斷言錯誤:

it('should init toBeTruthy', function() { 
    expect(GameManager.init()).to.be.ok; 
}); 

或將要與測試更加精確:

it('should init toBeTruthy', function() { 
    expect(GameManager.init()).to.be.true; 
}); 

另外,您可以參考這篇文章,可能是有益的

Why is my mocha/chai Error throwing test failing?

0

您的評論說:

I am not exporting GameManager since it is a simple Javascript object. Not using as Typescript export class.

您仍然需要導出它。無論它是否是一個簡單的JavaScript對象都是完全不相關的。您必須以適合Node.js模塊系統的方式編寫代碼。

使用你在問題中顯示的代碼,並固定在它的語法錯誤,我能得到你的第二個測試(一個用於init)工作,如果我添加到您的GameManager.js文件:

module.exports = GameManager; 

使用您在問題中顯示的代碼,從GameManager.js導出的值爲{}。所以當你做var GameManager = require("../GameManager.js");GameManager變量被賦值爲{}。因此GameManager.init的值爲undefined,因此它不是函數。添加上面顯示的行,將使得測試文件中的GameManager變量從GameManager.js文件中獲得GameManager的值,並且測試將通過。

(您沒有爲GameManager.commandString提供代碼,以便第一個測試仍然會失敗。只需添加代碼爲它得到它的工作。)

+0

在GameManager上增加了建議的行。js'保持'var GameManager = require(「../GameManager.js」);',但是測試總是會失敗'GameManager.gameType ='room';'如圖所示'undefined'和'TypeError:Can not set property'顯示gameType'undefined:'。由於某種原因,所有更改都無法正常工作。 – shaz