模拟依赖的构造函数 Jest [英] Mock a dependency's constructor Jest
问题描述
我是 Jest 的新手.我设法模拟了我自己的东西,但似乎被困在模拟模块中.特别是构造函数.
usage.js
const AWS = require("aws-sdk")cw = new AWS.CloudWatch({apiVersion: "2010-08-01"})...函数 myMetrics(params) {cw.putMetricData(params, function(err, data){})}
我想在测试中做这样的事情.
const AWS = jest.mock("aws-sdk")类 FakeMetrics {构造函数(){}putMetricData(foo,callback) {回调(空,耶!")}}AWS.CloudWatch = jest.fn( (props) => new FakeMetrics())
然而,当我在 usage.js
中使用它时,cw 是一个 mockConstructor
而不是 FakeMetrics
我意识到我的方法可能不那么惯用",所以我很乐意提供任何建议.
这是一个最小的例子https://github.com/ollyjshaw/jest_constructor_so
npm install -g jest
玩笑
问题是如何模拟模块.正如参考所述,><块引用>
在需要时使用自动模拟版本模拟模块.<...>返回用于链接的 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;
并断言如下:
expect(fakePutMetricData).toHaveBeenCalledTimes(1);
I'm a newbie to Jest. I've managed to mock my own stuff, but seem to be stuck mocking a module. Specifically constructors.
usage.js
const AWS = require("aws-sdk")
cw = new AWS.CloudWatch({apiVersion: "2010-08-01"})
...
function myMetrics(params) {
cw.putMetricData(params, function(err, data){})
}
I'd like to do something like this in the tests.
const AWS = jest.mock("aws-sdk")
class FakeMetrics {
constructor() {}
putMetricData(foo,callback) {
callback(null, "yay!")
}
}
AWS.CloudWatch = jest.fn( (props) => new FakeMetrics())
However when I come to use it in usage.js
the cw is a mockConstructor
not a FakeMetrics
I realise that my approach might be 'less than idiomatic' so I'd be greatful for any pointers.
This is a minimal example https://github.com/ollyjshaw/jest_constructor_so
npm install -g jest
jest
The problem is how a module is being mocked. As the reference states,
Mocks a module with an auto-mocked version when it is being required. <...> Returns the jest object for chaining.
AWS
is not module object but jest
object, and assigning AWS.CloudFormation
will affect nothing.
Also, it's CloudWatch
in one place and CloudFormation
in another.
Testing framework doesn't require to reinvent mock functions, they are already there. It should be something like:
const AWS = require("aws-sdk");
const fakePutMetricData = jest.fn()
const FakeCloudWatch = jest.fn(() => ({
putMetricData: fakePutMetricData
}));
AWS.CloudWatch = FakeCloudWatch;
And asserted like:
expect(fakePutMetricData).toHaveBeenCalledTimes(1);
这篇关于模拟依赖的构造函数 Jest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!