开玩笑-模拟Response.headers.get()

时间:2019-01-17 12:01:32

标签: javascript reactjs mocking jestjs

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

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

亲切的问候 迈克尔

1 个答案:

答案 0 :(得分:0)

您可以使用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 )
  }
}
相关问题