【问题标题】:How to test this specific situation in Jest如何在 Jest 中测试这种特定情况
【发布时间】:2020-04-11 03:48:07
【问题描述】:

我知道标题很糟糕,但我现在才知道如何解释这种情况。随意建议一个更好的标题,我会改变它。

所以我刚刚开始第一次进行测试,我正在使用 Jest。在我遇到这样的建筑之前一直做得很好

function f(n) {
    let g;
    if (n === 1) {
        g = () => console.log(`ok`);
    } else {
        g = () => {throw `not okay`;};
    }

    someEvent.listen(async () => {
        g();
    });
}

我不知道如何测试它,当我在f 中输入 1 以外的值时,它会抛出 not okay。据我所知,如果事件的回调不是异步的,那么最简单的expect(...).toBe(...) 就可以工作,但我无法弄清楚如何在异步的情况下做到这一点。

【问题讨论】:

  • 您的代码似乎很复杂,无法按照您想要的方式进行测试,因为在任何时候,您的 f 函数都会重新调整任何内容,因此您应该将 f 函数与 someEvent 侦听器分开。
  • someEvent 是从哪里来的?

标签: javascript unit-testing testing jestjs


【解决方案1】:

假设someEvent被定义为全局函数

global.someEvent = {
  listen: jest.fn(),
};

你可以这样测试它:

  1. 调用 f 函数,使用不同于 1 的值,您可以断言
  2. .listen 方法已被调用函数retrieve
  3. 来自.mock.calls 的给定处理程序断言如果它被调用了
  4. 应该以“不好”返回被拒绝的承诺
describe("the f function", () => {
  describe("called with something else", () => {
    beforeAll(() => {
      global.someEvent.listen.mockClear();
      f("x");
    });

    it("set the someEvent handler", () => {
      expect(global.someEvent.listen).toHaveBeenCalledWith(
        expect.any(Function)
      );
    });

    describe("when the someEvent triggers the handler", () => {
      let handler;
      beforeAll(() => {
        [[handler]] = global.someEvent.listen.mock.calls;
      });

      it("should return rejected promise with `not okay`", async () => {
        await expect(handler()).rejects.toEqual("not okay");
      });
    });
  });
});

working example

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多