我有一个从 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/