开玩笑-间谍功能里面的间谍功能

时间:2018-09-26 17:54:28

标签: mocking jestjs

我在另一个模拟函数中有一个链接的模拟函数,我需要监视两个函数,但是我不知道如何监视第二个。

这是一个示例:

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

2 个答案:

答案 0 :(得分:0)

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

诀窍是分开定义:

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

答案 1 :(得分:0)

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

赞:

public class Example : MonoBehaviour
{
    public EquipmentInventory equipmentInventory;

    [ContextMenu("Run")]
    public void Run()
    {
        equipmentInventory = EquipmentInventory.Instance;
    }
}

在应用中

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");