我有一个从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 )
}
}
在为同一问题寻找解决方案时结束了这里,但对于 Angular 2+。答案为我指明了正确的方向:
const headers = new HttpHeaders({ 'content-disposition': ' filename=email.eml' });
const body = new Blob(['a', 'b', 'c']);
const response: HttpResponse<Blob> = new HttpResponse<Blob>({
body,
headers,
});