javascript - 如何测试传递的函数?

标签 javascript unit-testing testing jestjs

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

最佳答案

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

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

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

Reference

关于javascript - 如何测试传递的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331433/

相关文章:

javascript - 在 Ionic 4 应用程序中按下硬件后退按钮时防止返回

Angular 2+,异步测试和 setTimeout

c# - IoC 预期接口(interface)的命名约定

grails - "Could not find ApplicationContext, configure Grails correctly first"

python - 如何使用输入调用测试函数?

javascript - 使用 event.target 返回一组项目(全局 div)中已修改的项目

javascript - 从 API 获取和输出数据的问题

visual-studio-2010 - 编码的 UI 错误 : The following element is not longer availabe

javascript - 将 JSON 加载到 Highcharts 饼图中

AngularJS 单元测试错误 : scope is undefined