【问题标题】:how to mock an imported class in my script from a jest test如何通过笑话测试在我的脚本中模拟导入的类
【发布时间】:2021-02-10 12:43:03
【问题描述】:

在我的一个构造函数中,我实例化了另一个类,但是为了单独测试,我需要模拟另一个类构造函数的实现。我尝试了几种方法,但都无法做到这一点。

下面的示例显然不起作用,因为它没有模拟从 foo.js 导入,但希望它显示了我正在尝试做的事情

./foo.js

import Bar from './bar.js'

export default class Foo {
  bar: undefined

  constructor() {
    this.bar = new Bar
  }
}

./bar.js

export default class Bar {
  constructor() {
    console.log('i do not want this to run')
  }  
}

./foo.test.js

import Foo from './foo.js'
import Bar from './bar.js'

jest.mock('./bar.js', () => {
  class BarMock {
    constructor() {
      console.log('i want this to run')
    }  
  }
})

describe('Foo', () => {
  it('should...', () => {
    const foo = new Foo

    expect(foo.bar).toBeInstanceOf(BarMock)
    expect(Bar).toBeCalled()
  })
})

【问题讨论】:

    标签: javascript ecmascript-6 jestjs mocking


    【解决方案1】:

    随便用

    jest.mock('./bar.js')
    

    如果您希望模拟在构造函数中调用console.log,请添加:

    Bar.prototype.constructor.mockImplementation(() => {
      console.log('i want this to run')
    })
    

    编辑:这是一个例子

    foo.test.js
    import Foo from "./foo.js";
    import Bar from "./bar.js";
    
    jest.mock("./bar.js");
    
    Bar.prototype.constructor.mockImplementation(() => {
      console.log("i want this to run");
    });
    
    describe("Foo", () => {
      it("should...", () => {
        const foo = new Foo();
    
        expect(foo.bar).toBeInstanceOf(Bar);
        expect(Bar).toBeCalled();
      });
    
      it("should be a mock function", () => {
        expect(jest.isMockFunction(Bar)).toEqual(true);
      });
    });
    

    working setup

    【讨论】:

    • 当它在foo.js 中运行时,这似乎不会模拟 Bar 类,仅适用于 foo.test.js 中的 Bar 类。即使我从我的测试中模拟它,当new Bar 在我的脚本中运行时,它是实际的 Bar 类,而不是被模拟的类
    • 哇,感谢您创建了该存储库!它绝对有效......但是我的实现没有。但现在我知道正确的方法并且知道它有效,我可以更好地排除故障。这个 repo 正在帮助我玩一个工作示例,我可以慢慢修改它以更接近我的实际代码。我认为我做的例子是我的代码的准确表示,但显然不是
    【解决方案2】:

    我不确定下面的这段代码是否是你需要的,

    但以下代码在我运行测试时调用了模拟的 console.log

    import Foo from './foo.js'
    import Bar from './bar.js'
    
    jest.mock('./bar.js')
    
    describe('Foo', () => {
      it('should...', () => {
        Bar.prototype.constructor.mockImplementation(() => {
          console.log('i want this to run')
        })
    
        const foo = new Foo
    
        expect(foo.bar).toBeInstanceOf(Bar);
        expect(Bar).toBeCalled()
      })
    })
    

    这是结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-26
      • 2019-04-13
      • 2017-08-26
      • 1970-01-01
      • 2021-10-30
      • 2019-03-26
      • 2018-07-28
      • 2020-10-14
      相关资源
      最近更新 更多