我如何使用笑话来模拟一个承诺的函数

时间:2019-01-21 04:07:42

标签: node.js mocking jestjs

我有一个非常简单的小实用程序功能

xml2JSON如下

import { promisify } from 'util'
import { parseString } from 'xml2js'

const xml2js = promisify(parseString)

const xmlToJSON = async xml => xml2js(xml)

export default xmlToJSON

我正在尝试以开玩笑的方式对其进行测试,以模仿出我不需要关心的内容

import * as util from 'util'
import * as xml2js from 'xml2js'

import xmlToJSON from './xmlToJSON'

jest.mock('util')
jest.mock('xml2js')

describe('xmlToJSON', () => {
  const promisifiedParseString = jest.fn()
  util.promisify = jest.fn(() => promisifiedParseString)
  const js = { some: 'result' }
  const xml = '<some>result</some>'
  let result

  beforeAll(async () => {
    promisifiedParseString.mockResolvedValue(js)
    result = await xmlToJSON(xml)
  })

  it('promisified the original parseString', () => {
    expect(util.promisify).toHaveBeenCalledWith(xml2js.parseString)
  })

  it('called the promisified parseString with the xml', () => {
    expect(promisifiedParseString).toHaveBeenCalledWith(xml)
  })

  it('returned the expected result', () => {
    expect(result).toEqual(js)
  })
})

但是我得到了错误

TypeError: xml2js is not a function

  4 | const xml2js = promisify(parseString)
  5 | 
> 6 | const xmlToJSON = async xml => xml2js(xml)
    |                                ^
  7 | 
  8 | export default xmlToJSON
  9 | 

我在做什么错了?

更新

根据以下建议,我尝试了更改导入顺序

import * as util from 'util'
import * as xml2js from 'xml2js'

jest.mock('util')
jest.mock('xml2js')
const promisifiedParseString = jest.fn()
util.promisify = jest.fn(() => promisifiedParseString)
import xmlToJSON from './xmlToJSON'

describe('xmlToJSON', () => {
  const js = { some: 'result' }
  const xml = '<some>result</some>'
  let result

  beforeAll(async () => {
    promisifiedParseString.mockResolvedValue(js)
    result = await xmlToJSON(xml)
  })

  it('promisified the original parseString', () => {
    expect(util.promisify).toHaveBeenCalledWith(xml2js.parseString)
  })

  it('called the promisified parseString with the xml', () => {
    expect(promisifiedParseString).toHaveBeenCalledWith(xml)
  })

  it('returned the expected result', () => {
    expect(result).toEqual(js)
  })
})

但这没什么作用

1 个答案:

答案 0 :(得分:0)

在导入使用文件的文件之前,您需要更改util.promisify的行为。

因此顺序应类似于:

util.promisify = jest.fn(() => promisifiedParseString)
import xmlToJSON from './xmlToJSON'