Javascript 如何在Jest中增加模拟构造函数的实例
我想在单元测试中增加但不完全替换模拟构造函数的实例 我想给这个实例添加一些值,但要保留自动模拟的善意 例如: A.jsJavascript 如何在Jest中增加模拟构造函数的实例,javascript,unit-testing,mocking,jestjs,Javascript,Unit Testing,Mocking,Jestjs,我想在单元测试中增加但不完全替换模拟构造函数的实例 我想给这个实例添加一些值,但要保留自动模拟的善意 例如: A.js module.exports = class A { constructor(value) { this.value = value; } getValue() { return this.value; } } 要获得一些自动模拟的惊人效果: jest.mock('./A'); 使用automock,实例有一个mocked.getValue(
module.exports = class A {
constructor(value) {
this.value = value;
}
getValue() {
return this.value;
}
}
要获得一些自动模拟的惊人效果:
jest.mock('./A');
使用automock,实例有一个mocked.getValue()
方法,但它们没有.value
属性
有文件证明的是:
将该方法用于A
:
jest.mock('./A');
const A = require('./A');
A.mockImplementation((value) => {
return { value };
});
it('does stuff', () => {
const a = new A();
console.log(a); // -> A { value: 'value; }
});
这样做的好处是,您可以对返回的值执行任何操作,如初始化.value
缺点是:
- 您不会免费获得任何自动模拟,例如,我需要将
我自己添加到实例中.getValue()
- 您需要为每个创建的实例使用不同的
mock函数,例如,如果我创建了jest.fn()
的两个实例,则每个实例都需要为a
方法使用自己的.getValue()
mock函数jest.fn()
未填充返回值()SomeClass.mock.instances
A.mockImplementation((值)=>{
const rv=Object.create(A.prototype);//以下内容适合我:
A.mockImplementation(value => {
const rv = {value: value};
Object.setPrototypeOf(rv, A.prototype);
return rv
})
事实证明,这是固定的(从jest 24.1.0开始),问题中的代码如预期的那样工作
概括地说,给定的类A
:
jest.mock('./A');
const A = require('./A');
A.mockImplementation((value) => {
return { value };
});
it('does stuff', () => {
const a = new A();
console.log(a); // -> A { value: 'value; }
});
A.js
module.exports = class A {
constructor(value) {
this.value = value;
}
getValue() {
return this.value;
}
}
module.exports=A类{
构造函数(值){
这个值=值;
}
设置值(值){
这个值=值;
}
}
此测试现在将通过:
A.test.js
module.exports = class A {
constructor(value) {
this.value = value;
}
getValue() {
return this.value;
}
}
jest.mock('./A');
常数A=要求('./A');
A.mockImplementation((值)=>{
const rv=Object.create(A.prototype);//{
常数a=新的a('some-value');
expect(A.mock.instances.length).toBe(1);
期望(a的一个实例)为(真);
expect(a).toEqual({value:'some value'});
a、 setValue(“另一个值”);
expect(a.setValue.mock.calls.length).toBe(1);
expect(a.setValue.mock.calls[0]).toEqual(['other-value']);
});
谢谢您的回答。问题已经解决,问题中的代码现在可以正常工作了。