javascript - 模拟 Response.headers.get()

标签 javascript reactjs mocking jestjs

我有一个从 http 响应头中提取文件名的方法:

export const getFilenameFromResponse = response => {
 const filenameRegex = /filename[^=\n]*=["](.*?)["]/;
 const matches = filenameRegex.exec(
   response.headers.get('Content-Disposition')
 );
 return matches != null && matches[1] ? matches[1] : '';
}; 
现在我打算用 Jest 编写一个单元测试。不幸的是, In 不能做类似的事情
const headers = myHeaders = new Headers([
    ['Content-Disposition', 'form-data; fileName="testfile.txt"']
]);
const response = new Response ({headers: newHeaders});
result = getFilenameFromResponse(response)
expect(result).ToEqual('testfile.txt';
因为测试失败,因为结果是一个空字符串。我想,这是由于响应对象的错误初始化。
有没有办法模拟response.headers.get() ?

最佳答案

您可以使用 spyOn设置 get 的行为功能:

const response = new Response ({headers: newHeaders});
const get = jest.spyOn(response.headers, 'get')
get.mockImplementation(()=> '')// do what ever `get` should to

另一种方法是不创建真正的 Response但只需传入一个普通对象:
const response = {
  headers: {
    get: jest.fn(()=> '')// do what ever `get` should to )
  }
}

关于javascript - 模拟 Response.headers.get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54235506/

相关文章:

php - JSON 中的关联数组解码

javascript - Mongodb javascript 表达式和 $where

javascript - 来自工厂的 React 组件名称

javascript - 无法在 this.setState() - React.js 中使用扩展运算符更新 json 属性

python - @Patch 装饰器与 pytest fixture 不兼容

unit-testing - Postman 不接受 `-` 作为模拟服务器请求的 URI 参数

javascript - gsub javascript中的字符串

javascript - 使用 $ne 查询后更新数组中的属性

javascript - 在 React 中,如何测试组件内的渲染方法

python - 如何使用 pytest 模拟 os.environ?