node.js - 如何使用 jest 模拟这个 http 请求?
问题描述
我是使用 Jest 进行单元测试的新手。如何模拟这个简单的 http 请求方法“getData”?这是课程:
const got = require("got")
class Checker {
constructor() {
this.url
this.logData = this.logData.bind(this);
this.getData = this.getData.bind(this);
}
async getData(url) {
const response = await got(url);
const data = await response.body;
return data;
}
async logData(first, second, threshold) {
let data = await this.getData(this.url)
console.log("received " + data.body);
}
}
我正在尝试模拟“getData”,以便为“logData”编写单元测试。我需要模拟整个“得到”模块吗?谢谢。
解决方案
如果您将调用更改got
为got.get
您应该能够进行如下工作测试:
const got = require('got');
const Checker = require('../index.js');
describe("some test", () => {
beforeEach(() => {
jest.spyOn(got, 'get').mockResolvedValue({ response: { body: { somekey: "somevalue" } } } );
});
it("works", async () => {
new Checker().getData();
expect(got.get).toBeCalledTimes(1);
})
})
推荐阅读
- amazon-web-services - ParsePy:在 Bitnami Parse Image 中获取 Rest API 密钥的位置
- angular - Angular 8:observable.pipe() 不再工作了?
- gtk3 - 更改顶部 GTKWindow 的字体/大小?
- java - 如何在没有root的情况下访问Android应用程序上的数据库
- excel - 从特定工作表索引开始循环遍历多个工作表
- ios - ScrollView 内容定位
- javascript - 在 Javascript 中使用 lambda 演算(使用教堂数字)的递归问题
- python - 在 PySpark 中使用字典进行情感分析
- android - Android-Room 可以自动创建迁移吗?
- swift - 如何根据集合视图中的单元格选择来控制表格视图的内容?