用 Jest 模拟 ajax 调用

时间:2021-06-16 08:05:52

标签: jquery ajax unit-testing jestjs mocking

我可以从 ajax 调用中获得存根 json 响应吗?

$.ajax(
    options,
    success: function(data){
        ...
    },
    error: function(data){
        ...
    }
)

我试过了,但没有成功。

$.ajax = jest.fn().mockImplementation((options) => {
    let instance = {
        done: (fn) => {
            if (options.success) fn("test passed");
            return instance;
        },
        fail: (fn) => {
            if (!options.success) fn("test failed");
            return instance;
        },
    };
    return instance;
});

我遇到了错误。

TypeError: Cannot read property 'toBe' of undefined

  37 |     )
  38 |
> 39 |     expect(response.toBe());
      |                     ^
  40 | });
  41 |

Ajax 函数似乎被替换为模拟。

我错过了什么?

JQuery:1.11.3 开玩笑:24.9.0

0 个答案:

没有答案
相关问题