【问题标题】:Jasmine toHaveBeenCalledWith doesn't work with fetch API and URLSearchParams from es6Jasmine toHaveBeenCalledWith 不适用于 es6 的 fetch API 和 URLSearchParams
【发布时间】:2017-09-21 16:48:24
【问题描述】:

我为使用 Fetch API 的 POST 调用编写了一个测试。为了检查我是否发送了良好的参数,我使用了 jasmine toHaveBeenCalledWith,这对于字符串主体来说可以正常工作。

当我将此字符串从 es6 而不是 Angular 更改为 URLSearchParams 对象时。测试变为红色,但预期调用和调用完全相等。

你有想法吗?

测试:

...
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})
...

【问题讨论】:

    标签: http jasmine tdd fetch-api


    【解决方案1】:

    使用 jasmine 的自定义相等测试器:

    在测试文件中添加这个函数:

    function customEquality(expected: any, value: any): boolean {
        return JSON.stringify(expected).trim() === JSON.stringify(value).trim();
    }
    

    在 beforeEach 中添加这一行:jasmine.addCustomEqualityTester(customEquality);

    并且正常使用toHaveBeenCalledWith

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 2012-11-15
      相关资源
      最近更新 更多