NodeJS 模拟依赖项的构造函数Jest

m4pnthwp  于 2023-08-04  发布在  Node.js
关注(0)|答案(3)|浏览(97)

我是一个新的笑话。我已经设法模仿我自己的东西,但似乎被困在模仿一个模块。特别是建筑师。
usage.js

const AWS = require("aws-sdk")
cw = new AWS.CloudWatch({apiVersion: "2010-08-01"})
...
function myMetrics(params) { 
  cw.putMetricData(params, function(err, data){})
}

字符串
我想在测试中做这样的事情。

const AWS = jest.mock("aws-sdk")
class FakeMetrics {
  constructor() {}
  putMetricData(foo,callback) {
    callback(null, "yay!")
  }
}

AWS.CloudWatch = jest.fn( (props) => new FakeMetrics())


但是,当我在usage.js中使用它时,cw是mockConstructor而不是FakeMetrics
我意识到我的方法可能“不太习惯”,所以我会对任何指针感到高兴。
这是一个最小示例https://github.com/ollyjshaw/jest_constructor_so
npm install -g jest
jest

s4n0splo

s4n0splo1#

上面的答案是有效的。然而,在使用jest一段时间后,我只会使用mockImplementation功能,这对mocking构造函数很有用。
下面的代码可以作为一个例子:

import * as AWS from 'aws-sdk';

jest.mock('aws-sdk', ()=> {
    return {
        CloudWatch : jest.fn().mockImplementation(() => { return {} })
    }
});

test('AWS.CloudWatch is called', () => {
    new AWS.CloudWatch();
    expect(AWS.CloudWatch).toHaveBeenCalledTimes(1);
});

字符串
请注意,在示例中,**new CloudWatch()**只返回一个空对象。

htzpubme

htzpubme2#

问题是如何模拟一个模块。如参考文献所述,
在需要时用自动模拟版本模拟模块。返回<...>用于链接的jest对象。
AWS不是模块对象,而是jest对象,分配AWS.CloudFormation不会有任何影响。
另外,在一个地方是CloudWatch,在另一个地方是CloudFormation
测试框架不需要重新发明模拟函数,它们已经存在了。它应该类似于:

const AWS = require("aws-sdk");
const fakePutMetricData = jest.fn()
const FakeCloudWatch = jest.fn(() => ({
    putMetricData: fakePutMetricData
}));                        
AWS.CloudWatch = FakeCloudWatch;

字符串
并Assert:

expect(fakePutMetricData).toHaveBeenCalledTimes(1);

lxkprmvk

lxkprmvk3#

根据文档,mockImplementation也可以用来模拟类构造函数:

// SomeClass.js
module.exports = class SomeClass {
  method(a, b) {}
};

// OtherModule.test.js
jest.mock('./SomeClass'); // this happens automatically with automocking
const SomeClass = require('./SomeClass');
const mockMethod= jest.fn();
SomeClass.mockImplementation(() => {
  return {
    method: mockMethod,
  };
});

const some = new SomeClass();
some.method('a', 'b');
console.log('Calls to method: ', mockMethod.mock.calls);

字符串
如果你的类构造函数有参数,你可以将jest.fn()作为参数传递(例如:const some = new SomeClass(jest.fn(), jest.fn());

相关问题