Jest Uncovered Lines - 我如何测试这些线..?

Ste*_*ast 8 javascript unit-testing jestjs

我正在使用Jest覆盖选项,我得到:

--------------------------|----------|----------|----------|----------|----------------|
File                      |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
--------------------------|----------|----------|----------|----------|----------------|
progress-bar.js           |      100 |       75 |      100 |      100 |             17 |
--------------------------|----------|----------|----------|----------|----------------|
Run Code Online (Sandbox Code Playgroud)

所以我有17条未覆盖的线,但我不知道如何掩盖它们.

进步,bar.js

import ProgressBar from 'progress'
import isNumber from 'lodash/isNumber'
import config from '../../config/global'

function progressBar (total) {
  if (!isNumber(total)) throw new Error(`progressBar() 'total' arg is not a number.`)

  const barCfg = config.progressBar

  const tokens = `${barCfg.bar} ${barCfg.info}`

  const options = {
    width: barCfg.width,
    total: total || 1,
    complete: barCfg.complete,
    incomplete: barCfg.incomplete
  }

  const bar = new ProgressBar(tokens, options)

  bar.render()

  return bar
}

export default progressBar
Run Code Online (Sandbox Code Playgroud)

进步,bar.test.js

import ProgressBar from 'progress'
import progressBar from './progress-bar'

describe('progressBar()', () => {
  test('returns instanceof ProgressBar', () => {
    const actual = progressBar(5) instanceof ProgressBar
    const expected = true
    expect(actual).toBe(expected)
  })

  test('throw error if arg "total" is not a number', () => {
    expect(() => { progressBar('moo') }).toThrow()
    expect(() => { progressBar(null) }).toThrow()
  })

  test('progress bar progress/ticking', () => {
    const bar = progressBar(5)
    expect(bar.total).toBe(5)
    expect(bar.curr).toBe(0)
    bar.tick()
    expect(bar.curr).toBe(1)
    bar.tick()
    expect(bar.curr).toBe(2)
    bar.tick()
    expect(bar.curr).toBe(3)
    bar.tick()
    expect(bar.curr).toBe(4)
    bar.tick()
    expect(bar.curr).toBe(5)
    expect(bar.complete).toBe(true)
  })
})
Run Code Online (Sandbox Code Playgroud)

所以我正在测试参数并返回值.

如何全面测试此功能,包括17行......?

mik*_*ana 18

如果您知道未覆盖的行号,但无法弄清楚该行未覆盖的原因:

如果“未覆盖线”为黄色,则表示它们被部分覆盖。您可以通过生成覆盖范围的 HTML 报告来找出未覆盖哪些特定属性:

npx jest --coverage --coverageDirectory='coverage'
Run Code Online (Sandbox Code Playgroud)

然后打开coverage/lcov-report/index.html它将显示未经测试的特定代码路径

就我而言,一个函数有一个默认的 arg foo = false,它正在使用不同的 arg 值进行测试,但默认值没有经过测试,因此它显示为黄色。


Ste*_*ast 15

好吧,我现在坐在角落里戴着我的笨蛋帽子.

发现这个:https://github.com/istanbuljs/nyc/issues/35#issuecomment-121008298

未覆盖的行= 17不是未覆盖行的计数,它是只有一个值的列表,即第17行:total: total || 1,.

固定...

test('passing zero forces the default total of 1', () => {
  const bar = progressBar(0)
  expect(bar.total).toBe(1)
})
Run Code Online (Sandbox Code Playgroud)