【问题标题】:How to mock call to constructor of class in 3rd party module called from the same module using jest如何在使用 jest 从同一模块调用的第 3 方模块中模拟对类的构造函数的调用
【发布时间】:2021-09-14 20:54:27
【问题描述】:

我有一个像这样的第 3 方模块

class Test {
   async doSomething() {}
}

export const testObject = new Test();  <--- I want to mock this part because constructor requires some input which I don't want to provide as it is not required for tests

导入上述模块的另一个模块

import { testObject } from 'module1';

function foo() {
    testObject.doSomething()
}

现在我正在尝试编写如下所示的单元测试

describe('test', ()=> {
    test('', ()=> {
        foo()
    })
})

new Test() 依赖于我不想提供的一些外部输入,因此当我运行测试时,由于缺少输入而失败,我不确定如何阻止 new Test() 按原样执行,而是应该运行模拟函数

【问题讨论】:

    标签: javascript node.js unit-testing ts-jest


    【解决方案1】:

    试试这样的。如果您运行此测试,它将通过:

    类文件。

    class SoundPlayer {
      foo: string
      constructor() {
        this.foo = 'bar'
      }
    
      playSoundFile(fileName: any) {
        console.log('Playing sound file ' + fileName)
      }
    }
    
    export const testObject = new SoundPlayer()
    

    函数文件

    import { testObject } from './test'
    
    export default function test() {
      testObject.playSoundFile('testing')
    }
    

    测试文件

    import { testObject } from '../test'
    import test from '../test1'
    jest.mock('../test')
    
    it('should run test', () => {
      test()
      expect(testObject.playSoundFile).toHaveBeenCalledTimes(1)
    })
    
    

    这是一个非常基本的示例,您可以使用 4 种不同的方式进行模拟。 查看 Jest 文档:https://jestjs.io/docs/es6-class-mocks#the-4-ways-to-create-an-es6-class-mock

    【讨论】:

    • 我不想在 testObject 上模拟任何方法。我想模拟对 Test 类的构造函数的调用。但我没有调用构造函数。它通过export const testObject = new Test();这一行在模块内部被调用,我想模拟这个调用,因为构造函数正在接受我不想提供的输入,因为测试不需要该功能
    • 到目前为止您尝试过什么?当您说第三方时,您的意思是它是一个 npm 模块吗?如果不是,是否可以不导出构造函数的结果?你可以模拟构造函数而不是模拟构造函数的结果。
    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 2018-02-19
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多