如何在茉莉花和咖啡中编写开关盒的单元测试

How to write unit test for switch case in jasmine and coffee

本文关键字:开关 单元测试 茉莉花 咖啡      更新时间:2023-09-26

我是jasminecoffee的新手。

我的问题在别人看来很熟悉,但其实不然。

请看看我的代码片段

<<p> 咖啡代码/strong>
$scope.changeText = ->
  $timeout $scope.changeText, 5000
  id = parseInt(Math.random() * 4)
  switch id
    when 0
      $scope.home.banner.mainHead =  'Some Heading'
      $scope.home.banner.subHead =  'Some more text'
    when 1
      $scope.home.banner.mainHead =  'Some other Heading'
      $scope.home.banner.subHead =  'Some more text'
    when 2
      $scope.home.banner.mainHead =  'Another Heading'
      $scope.home.banner.subHead =  'Another Text'
    when 3
      $scope.home.banner.mainHead =  'Another Heading 1'
      $scope.home.banner.subHead =  'Text text text'
  return
$timeout($scope.changeText, 5000)

如何在jasmine中开始编写测试用例?

您的代码片段的问题是,它生成一个随机的id,因此它不能被确定性地测试。但是,您可以测试的是mainHeadsubHead相对于id是否发生了相应的变化。因此,我将该代码片段拆分为一个可测试的函数,其中包含switch语句和其他语句:

咖啡:

getBanner = (id) -> 
    banner = {}
    switch id
        when 0
            banner.mainHead = "Some Heading"
            banner.subHead  = "Some more text"
        when 1
            banner.mainHead = "Some other Heading"
            banner.subHead  = "Some more text"
        when 2
            banner.mainHead = "Another Heading"
            banner.subHead  = "Another text"
        when 3
            banner.mainHead = "Another Heading 1"
            banner.subHead  = "Text text text"
    banner
$scope.changeText = ->
    id = parseInt(Math.random() * 4)
    $scope.home.banner = getBanner(id)
# $interval might be better in your use case than $timeout
$interval $scope.changeText, 5000

测试:

describe "getBanner", ->
    it "should return mainHead/subHead", ->
        banner = getBanner(0)
        expect(banner.mainHead).toEqual("Some Heading")
        expect(banner.subHead).toEqual("Some more text")
        banner = getBanner(1)
        # ...
    it "should return empty banner on wrong id", ->
        # testing edge cases
        banner = getBanner(-1)
        expect(Object.keys(banner).length).toEqual(0)