利用 jest 寫測試


Posted by YongChenSu on 2020-12-06

安裝 jest

yarn add --dev jest


寫好欲測試的程式

repeat.js

function repeat(str, times) {
  let result = ''
  for (let i=0; i<times; i++) {
    result += str
  }
  return result
}

module.exports = repeat


repeat.test.js

var repeat = require('./repeat')
// console.log(repeat('a', 5))

test('a 重複 5 次要等於 aaaaa', function() {
  expect(repeat('a', 5)).toBe('aaaaa')
})


npm run test

在 package.json\scripts 中,將 "test" 的值修改為 "jest",以後 npm run start 會利用 jest 找尋所有 test.js 的檔案並做測試。

// package.json\scripts
{
  ...,
  "scripts": {
    ...,
  "test": "jest",
  }
}

npm run test

若只想測試單一檔案,test 後面接著檔名即可。

// package.json\scripts
{
  ...,
  "scripts": {
    ...,
  "test": "jest repeat.test.js",
  }
}


npx jest

若 npm 的版本較新,可支援在 terminal 直接用 npx jest

而直接在 terminal 直接下 jest 一樣是不行的,因為這樣是在系統中找,系統中並沒有 jest 這個指令

將相同類型的測試放在一起 (describe)

describe('測試 repeat', function() {
  test('a 重複 5 次要等於 aaaaa', function() {
    expect(repeat('a', 5)).toBe('aaaaa')
  })

  test('"" 重複 10 次要等於 ""', function() {
    expect(repeat('', 10)).toBe('')
  })

  test('ABC 重複 3 次要等於 ABCABCABC', function() {
    expect(repeat('ABC', 3)).toBe('ABCABCABC')
  })
})



測試驅動開發 (TTD)

TTD (Test-driven Development)
先寫測試再寫程式

參考資源


#程式導師實驗計畫第四期 #前端 #測試 #Jest







Related Posts

Day03:從迴圈看 bytecode

Day03:從迴圈看 bytecode

[Release Notes] 20200924_v1 - Fix blog post serie checkbox bug & add publish type modal

[Release Notes] 20200924_v1 - Fix blog post serie checkbox bug & add publish type modal

JavaScript Drum Kit

JavaScript Drum Kit


Comments