Jasmine toHaveBeenCalledWith 不适用于来自 es6 的 fetch API 和 URLSearchParams
Jasmine toHaveBeenCalledWith doesn't work with fetch API and URLSearchParams from es6
我用 Fetch API 为 POST 调用编写了一个测试。为了检查我是否发送了正确的参数,我使用 jasmine toHaveBeenCalledWith 并且它可以很好地处理字符串主体。
当我将此字符串从 es6 更改为 URLSearchParams 对象时,而不是 Angular。测试变为红色,但预期调用和调用完全相等。
你有想法了吗?
测试:
...
mockHttp = {post: null} as Http;
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let searchParams = new URLSearchParams();
searchParams.set("refresh_token", token.refreshToken);
searchParams.set("grant_type", "refresh_token");
searchParams.set("client_id", "DriverApp");
expect(mockHttp.post).toHaveBeenCalledWith("ENDPOINT_API_URL_REFRESH_TOKEN", searchParams, {headers: headers})
...
使用 jasmine 的自定义相等性测试器:
在测试文件中添加这个函数:
function customEquality(expected: any, value: any): boolean {
return JSON.stringify(expected).trim() === JSON.stringify(value).trim();
}
在 beforeEach 添加这一行:jasmine.addCustomEqualityTester(customEquality);
并正常使用toHaveBeenCalledWith
我用 Fetch API 为 POST 调用编写了一个测试。为了检查我是否发送了正确的参数,我使用 jasmine toHaveBeenCalledWith 并且它可以很好地处理字符串主体。
当我将此字符串从 es6 更改为 URLSearchParams 对象时,而不是 Angular。测试变为红色,但预期调用和调用完全相等。
你有想法了吗?
测试:
...
mockHttp = {post: null} as Http;
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let searchParams = new URLSearchParams();
searchParams.set("refresh_token", token.refreshToken);
searchParams.set("grant_type", "refresh_token");
searchParams.set("client_id", "DriverApp");
expect(mockHttp.post).toHaveBeenCalledWith("ENDPOINT_API_URL_REFRESH_TOKEN", searchParams, {headers: headers})
...
使用 jasmine 的自定义相等性测试器:
在测试文件中添加这个函数:
function customEquality(expected: any, value: any): boolean {
return JSON.stringify(expected).trim() === JSON.stringify(value).trim();
}
在 beforeEach 添加这一行:jasmine.addCustomEqualityTester(customEquality);
并正常使用toHaveBeenCalledWith