gpt4 book ai didi

javascript - Jest : How to get arguments passed to mock constructor?

转载 作者:行者123 更新时间:2023-11-30 19:51:52 25 4
gpt4 key购买 nike

如果我想创建一个 ES6 类的实例方法的模拟实现,我会这样做

// ExampleClass.js
export class ExampleClass {
constructor(someValue) {
this.a = someValue;
}

exampleMethod(anotherValue) {
// do something with 'anotherValue'
}
}

// OtherModule.js
import {ExampleClass} from './ExampleClass';
export const fooBar = () => {
const ex = new ExampleClass("hello world");
ex.exampleMethod("another value");
};

// ExampleClass.test.js
import {fooBar} from './OtherModule';
import {ExampleClass} from './ExampleClass';
jest.mock('./ExampleClass');

it('try to create a mock of ExampleClass', () => {
ExampleClass.mockClear();

fooBar();

// to verify values for of instance method "exampleMethod" of ExampleClass instance
expect(ExampleClass.mock.instances[0].exampleMethod.calls.length).toBe(1);
expect(ExampleClass.mock.instances[0].exampleMethod.calls[0][0]).toBe("another value");

// How to verify values for **constructor** of ExampleClass ?????
// expect(ExampleClass.mock.instances[0].constructor.calls.length).toBe(1);
// expect(ExampleClass.mock.instances[0].constructor.calls[0][0]).toBe("another value");
});

我不知道该怎么做(以及在注释代码中提到的)是如何监视/访问构造函数的值(而不仅仅是实例方法)。

任何帮助将不胜感激! ❤

最佳答案

ExampleClass 是构造函数,因为整个模块是自动模拟的,所以它已经设置为模拟函数:

import {fooBar} from './OtherModule';
import {ExampleClass} from './ExampleClass';
jest.mock('./ExampleClass');

it('try to create a mock of ExampleClass', () => {
ExampleClass.mockClear();

fooBar();

// to verify values for of instance method "exampleMethod" of ExampleClass instance
expect(ExampleClass.mock.instances[0].exampleMethod.mock.calls.length).toBe(1); // SUCCESS
expect(ExampleClass.mock.instances[0].exampleMethod.mock.calls[0][0]).toBe("another value"); // SUCCESS

// Verify values for **constructor** of ExampleClass
expect(ExampleClass.mock.calls.length).toBe(1); // SUCCESS
expect(ExampleClass.mock.calls[0][0]).toBe("hello world"); // SUCCESS
});

关于javascript - Jest : How to get arguments passed to mock constructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com