首页 > 解决方案 > 如何测试通过的功能?

问题描述

doc 是 pdfkit 文档的一个实例...

import PDFDocument from 'pdfkit'
const doc = new PDFDocument()

...它被传递给我的函数:

export const outputTitle = (doc, title) => {
  if (!title) return null

  doc
    .fontSize(15)
    .font('Helvetica-Bold')
    .text(title, 380, 160)
}

现在我需要使用 jest 为这个函数编写单元测试。

describe('outputTitle()', () => {
  const doc = jest.fn()

  test('should return null if parameter title is missing', () => {
    // SETUP
    const title = undefined
    // EXECUTE
    const result = outputTitle(doc, title)
    // VERIFY
    expect(result).toBeNull()
  })

  test('should call doc()', () => {
    // ???
  })
})

但是我如何测试第二部分,即传递标题值的情况?我认为我的嘲笑doc是错误的。

标签: javascriptunit-testingtestingjestjs

解决方案


describe('outputTitle()', () => {
  const textSpy = jest.spyOn(doc, 'text');

  test('should call doc with title', () => {
      outputTitle(doc, 'some title');

      expect(textSpy).toBeCalledWith('some title');
    });
})

参考


推荐阅读