Javascript 如何监视类构造函数笑话?

Javascript 如何监视类构造函数笑话?,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,对于类中的方法,我们可以使用 jest.spyOn(Foo,'bar')监视该方法。构造函数呢?我们如何监视对象是如何实例化的 我想没有官方的办法。我个人就是这样做的: export class Foo { public static bar() { doSomething(); } constructor(paramA, paramB) { } } 然后我可以检查间谍: const spy = jest.fn() function Moc

对于类中的方法,我们可以使用
jest.spyOn(Foo,'bar')
监视该方法。构造函数呢?我们如何监视对象是如何实例化的

我想没有官方的办法。我个人就是这样做的:

export class Foo {
    public static bar() {
        doSomething();
    }

    constructor(paramA, paramB) {

    } 
}
然后我可以检查间谍:

const spy = jest.fn()
function Mock (...args) {
  spy(...args)
  Constructor.apply(this, args)
}
Mock.prototype = Constructor.prototype
其实有一种方法:)
甚至在官方文件中:

下面是如何使用代码执行此操作:

expect(spy).toHaveBeenCalledWith('firstArg', 'secondArg')

@gillyb是对的,只是忘了“模拟”Foo模块

// Foo.js
export class Foo {
    public static bar() {
        doSomething();
    }

    constructor(paramA, paramB) {

    } 
}

// Foo.spec.js
import Foo from './Foo.js';

it('test something...', () => {
    // Assuming we did something that called our constructor
    expect(Foo).toHaveBeenCalledTimes(1);
});

引用自

如果您确实想监视构造函数,可以执行以下操作:

// Actual Implementation 
import { ModuleToMock} from 'module-to-mock'

const test = new ModuleToMock('value1', 'value2')

test.setUser({ name: 'test', address: 'myTest' })

// test case using jest 
 import { ModuleToMock} from 'module-to-mock'
 jest.mock('module-to-mock')

// constructor response 
   const mockedModuleResponse = {
   setUser: jest.fn(), 
   }

ModuleToMock.mockImplementation(() => mockedModuleResponse)

执行此操作时,您将收到一个错误:“值必须是模拟函数或间谍”。我猜您已经设置了
automock:true
以模拟jest配置中的所有内容。在本例中,构造函数将
be
Foo
?使用“jest.mock”可以用模拟覆盖整个类。但是有没有一种方法可以在不覆盖类的情况下监视构造函数呢?这样的话,这个班照常上课,却有人在开玩笑?因为在我的用例中,我需要类像往常一样工作,但我不想总是检查属性设置是否正确,以便检查它是否使用正确的参数调用。因此,如果我能检查构造函数是否被正确调用,那就太酷了。这应该是可以接受的答案。
// Actual Implementation 
import { ModuleToMock} from 'module-to-mock'

const test = new ModuleToMock('value1', 'value2')

test.setUser({ name: 'test', address: 'myTest' })

// test case using jest 
 import { ModuleToMock} from 'module-to-mock'
 jest.mock('module-to-mock')

// constructor response 
   const mockedModuleResponse = {
   setUser: jest.fn(), 
   }

ModuleToMock.mockImplementation(() => mockedModuleResponse)
// MyClass.js

export class MyClass {
  constructor() {
    console.log("constructing");
  }
}

// MyClass.test.js

import * as MyClassModule from './MyClass';

const MyClass = MyClassModule.MyClass;

test('the constructor is called', () => {
  const constructorSpy = jest.spyOn(MyClassModule, 'MyClass');
  new MyClass();
  expect(constructorSpy).toHaveBeenCalledTimes(1);
});