模拟依赖项的构造函数Jest [英] Mock a dependency's constructor Jest

查看:143
本文介绍了模拟依赖项的构造函数Jest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Jest的新手.我已经设法模拟了自己的东西,但是似乎在模拟模块时被卡住了.特别是构造函数.

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())

但是,当我在usage.js中使用它时,cw是mockConstructor而不是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.

这是一个最小的示例 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不是模块对象,而是jest对象,分配AWS.CloudFormation不会有任何影响.

AWS is not module object but jest object, and assigning AWS.CloudFormation will affect nothing.

此外,它在一个位置为CloudWatch,在另一个位置为CloudFormation.

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;

并断言如下:

expect(fakePutMetricData).toHaveBeenCalledTimes(1);

这篇关于模拟依赖项的构造函数Jest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆