【问题标题】:How to test for a passed function?如何测试通过的功能?
【发布时间】:2019-05-27 19:19:28
【问题描述】:

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 的模拟是错误的。

【问题讨论】:

    标签: javascript unit-testing testing jestjs


    【解决方案1】:
    describe('outputTitle()', () => {
      const textSpy = jest.spyOn(doc, 'text');
    
      test('should call doc with title', () => {
          outputTitle(doc, 'some title');
    
          expect(textSpy).toBeCalledWith('some title');
        });
    })
    

    Reference

    【讨论】:

    • 但这并不是在测试我的文档链。还是我误会了你?
    • 我从未使用过 pdfkit,但这就是您测试函数并开玩笑地跟踪对该函数的调用的方式。
    • 当然,但是我将尝试测试的函数是使用传递的变量 'doc' 而不是 new PDFDocument
    • 附加了一些来自 pdfkit 的测试作为参考,这可能会有所帮助
    • 编辑了我的答案以合并传递的文档
    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多