javascript 在玩笑中模拟静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50421732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:05:44  来源:igfitidea点击:

Mocking up static methods in jest

javascriptjestjs

提问by Clemens

I am having trouble mocking up a static method in jest. Immagine you have a class A with a static method:

我在开玩笑地模拟静态方法时遇到了麻烦。想象一下,您有一个带有静态方法的 A 类:

export default class A {
  f() {
    return 'a.f()'
  }

  static staticF () {
    return 'A.staticF()'
  }
}

And a class B that imports A

以及导入 A 的 B 类

import A from './a'

export default class B {
  g() {
    const a = new A()
    return a.f()  
  }

  gCallsStaticF() {
    return A.staticF()
  }
}

Now you want to mock up A. It is easy to mock up f():

现在你想模拟 A。模拟 f() 很容易:

import A from '../src/a'
import B from '../src/b'

jest.mock('../src/a', () => {
  return jest.fn().mockImplementation(() => {
    return { f: () => { return 'mockedA.f()'} }
  })
})

describe('Wallet', () => {
  it('should work', () => {
    const b = new B()
    const result = b.g()
    console.log(result) // prints 'mockedA.f()'
  })
})

However, I could not find any documentation on how to mock up A.staticF. Is this possible?

但是,我找不到任何关于如何模拟 A.staticF 的文档。这可能吗?

回答by Peter Stonham

You can just assign the mock to the static method

您可以将模拟分配给静态方法

import A from '../src/a';
import B from '../src/b';

jest.mock('../src/a');

describe('Wallet', () => {
  it('should work', () => {
    const mockStaticF = jest.fn();
    mockStaticF.mockReturnValue('worked');

    A.staticF = mockStaticF;

    const b = new B();

    const result = b.gCallsStaticF();
    expect(result).toEqual('worked');
  });
});

回答by mandarin

I managed to mock it in a separate file in the __mocks__folder using prototyping. So you would do:

我设法__mocks__使用原型在文件夹中的一个单独文件中模拟它。所以你会这样做:

function A() {}
A.prototype.f = function() {
    return 'a.f()';
};
A.staticF = function() {
    return 'A.staticF()';
};
export default A;