我怎样才能开玩笑地嘲笑一个图书馆?

时间:2019-02-15 08:13:12

标签: javascript reactjs mocking jestjs enzyme

我正在尝试通过玩笑测试来模拟文件类型库。在我的javascript文件中,我通过以下方式使用此库:

import * as fileType from 'file-type';

....
const uploadedFileType = fileType(intArray);

然后,按照我的笑话,我正在做:

jest.mock('file-type');
import * as fileType from 'file-type';

,然后尝试通过以下方式模拟响应:

fileType = jest.fn();
fileType.mockReturnValue({ ext: 'jpg' });

但是,出现错误"fileType" is read-only.

有人对我在做什么错有想法吗?预先感谢。

2 个答案:

答案 0 :(得分:0)

如果在所有测试中只需要相同的返回类型,则可以这样模拟它

jest.mock('fileType', ()=> () => ({
  ext: 'jpg'
}))

这将模拟该模块,因此fileType()将始终返回{ext: 'jpg'}

如果在测试期间需要不同的返回值,则需要对模块进行模拟,以便它返回一个间谍,您可以稍后在测试中使用mockImplementation设置模拟结果:

import fileType from 'fileType'
jest.mock('fileType', ()=> jest.fn())

fileType.mockImplementation(() => ({
  ext: 'jpg'
}))

答案 1 :(得分:0)

玩笑测试开始时,您拥有:import * as fileType from 'file-type';

此行创建一个名为fileType的(常量)变量,该变量无法被重新分配。这意味着,当您拥有fileType = jest.fn()的时候,您将得到"fileType" is read-only的错误-因为您无法再将fileType分配给其他东西。

要模拟fileType,您可以执行以下操作:

jest.mock('file-type')
import fileType from 'file-type'

const mockValue = { ext: 'jpg' }
fileType.mockImplementation(() => (mockValue))

const BUFFER = Buffer.from([0x00, 0x01])

describe('Mocks file-type', () => {
  it("should equal { ext: 'jpg' }", () => {
    expect(fileType(BUFFER)).toEqual(mockValue)
  })
})

最终得到的是一个模拟的fileType模块(实际上只是一个函数),无论传递给它什么,它都将返回{ ext: 'jpg' }

请另外注意,您的import * as fileType from 'file-type'行(在您的用法代码和测试代码中)可能都不是您想要的。这将创建一个名为fileType的对象,该对象具有一个名为default的功能-这意味着您将需要通过以下方式使用它:

fileType.default(buffer)

如果您想以传统方式使用file-type,则可以使用import fileType from 'file-type'进行导入-这将为您提供所需的fileType()函数。

相关问题