2016-04-20 39 views
0

前言:上週我開始修改JavaScript,所以這可能是也可能不是一個愚蠢的問題(雖然我會打賭前者)。在JavaScript中測試無效參數w/Chai

我創建了這種方法,返回getDayOfTheWeekFromDate初始化爲Date()的星期幾。我試圖用chai創建一個測試,看看它是否被喂入一個虛假參數(如字符串)時會發生什麼。

兩個問題:

  1. 我是否正確檢查類型?
  2. 我該如何測試getDayOfTheWeekFromDatechai的虛假參數?

    DateHelper.prototype.getDayOfTheWeekFromDate = function(inputDate) { 
        if (inputDate instanceof Date) { 
         inputDate = new Date(); 
         var dayOfTheWeek = inputDate.getDay(); 
    
         switch(dayOfTheWeek) { 
          case 0: return "Sunday"; 
          case 1: return "Monday"; 
          case 2: return "Tuesday"; 
          case 3: return "Wednesday"; 
          case 4: return "Thursday"; 
          case 5: return "Friday"; 
          case 6: return "Saturday"; 
          default: return; 
         } 
        } else { 
         // I'm shooting for doing nothing if the input isn't a Date() 
         // How would I test this? 
         return; 
        } 
    }; 
    

我有一個測試類設置爲測試日期輔助類。

'use strict'; 
var chai = require('chai'); 
var expect = chai.expect; 
var DateHelper = require('../date_helper'); 
chai.config.includeStack = true; // true enables stack trace 

describe('DateHelper', function() { 

    context('With a valid date value, getDayOfTheWeekFromDate', function() { 
     it('should return Tuesday', function() { 
      expect(subject.getDayOfTheWeekFromDate(new Date())).to.eq('Tuesday'); 
     }); 
    }); 
}); 

我試過這個,但是當我給初始化程序一個字符串時,控制檯假髮出來,不知道什麼是undefined。我應該怎麼在這裏?:測試

context('With a invalid date value, getDayOfTheWeekFromDate', function() { 
    it('should return nothing', function() { 
     expect(subject.getDayOfTheWeekFromDate('bogusArgument').to.be.undefined; 
    }); 
}); 

回答

1

這將正常工作,如果你把所有的括號平衡:

expect(subject.getDayOfTheWeekFromDate('bogusArgument')).to.be.undefined; 
          //      ^
          // this one was missing/
+0

謝謝!我的棉絨沒有選擇。優秀的眼睛!我創建的方法是否合理,是否遵循約定? – Adrian

+1

@AdrianB我個人會刪除包含'else'和'default'的分支,並且只需將fall-through'return;'作爲函數的最後一行。 – zerkms