【问题标题】:jest - spy function inside mock functionjest - 模拟函数中的间谍函数
【发布时间】:2019-12-20 23:12:45
【问题描述】:

我在另一个模拟函数中有一个链式模拟函数,我需要监视它们,但我不知道如何监视第二个。

这是一个例子:

res = {
  status: jest.fn(() => {
    return {
      json: jest.fn()
    }
  })
}

expect(res.status).toBeCalled() // This works
expect(res.status.json).toBeCalled() // This does not
expect(res.status().json).toBeCalled() // This does neither

【问题讨论】:

    标签: mocking jestjs


    【解决方案1】:

    现在你可以使用https://jestjs.io/docs/en/mock-function-api#mockfnmockreturnthis

    像这样:

    const res = {
      status: jest.fn().mockReturnThis(),
      send: jest.fn()
    };
    
    // call function and pass res
    
    expect(res.status).toHaveBeenCalledTimes(1);
    expect(res.status).toHaveBeenCalledWith(200);
    expect(res.send).toHaveBeenCalledTimes(1);
    expect(res.send).toHaveBeenCalledWith("Something");
    

    应用内:

    res.status(200).send("Something");
    

    【讨论】:

      【解决方案2】:

      我在这里找到了解决方案:Spying on chained method calls with Jest not working

      诀窍是分开定义:

      json = { json: jest.fn() }
      res = {
        status: jest.fn(() => json)
      }
      

      【讨论】:

      • 谢谢,这为我节省了很多时间。想解释一下为什么这行得通吗?将对象存储到变量有什么魔力?
      猜你喜欢
      • 2021-11-20
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2017-11-15
      • 2022-07-22
      • 2021-08-27
      相关资源
      最近更新 更多