开玩笑 - 具有对象为参数的模拟函数

发布于 2025-01-17 09:39:37 字数 435 浏览 0 评论 0原文

如何模拟一个具有对象作为参数并返回承诺的函数?

示例:

type FuncProps = {
  type: 'a' | 'b';
  isSelected: boolean;
  isDataIncluded: boolean;
};

type Props = {
  onDoSomething: ({ type, isSelected, isDataIncluded }: FuncProps) => Promise<void>;
};

当我这样做时,我会遇到错误:

const onDoSomethingMock = jest.fn(({ type: 'a', isSelected: true, isDataIncluded: false }) => Promise.resolve());

How can I mock a function which has an object as an argument and returns a promise?

Example:

type FuncProps = {
  type: 'a' | 'b';
  isSelected: boolean;
  isDataIncluded: boolean;
};

type Props = {
  onDoSomething: ({ type, isSelected, isDataIncluded }: FuncProps) => Promise<void>;
};

I get an error when I do this:

const onDoSomethingMock = jest.fn(({ type: 'a', isSelected: true, isDataIncluded: false }) => Promise.resolve());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囍笑 2025-01-24 09:39:37

应该是:

type FuncProps = {
  type: 'a' | 'b';
  isSelected: boolean;
  isDataIncluded: boolean;
};

type Props = {
  onDoSomething: ({ type, isSelected, isDataIncluded }: FuncProps) => Promise<void>;
};

describe('71625454', () => {
  test('should pass', async () => {
    const onDoSomethingMock: Props['onDoSomething'] = jest.fn(({ type, isSelected, isDataIncluded }: FuncProps) =>
      Promise.resolve()
    );
    await onDoSomethingMock({ type: 'a', isSelected: true, isDataIncluded: false });
    expect(onDoSomethingMock).toBeCalled();
  });
});

It should be:

type FuncProps = {
  type: 'a' | 'b';
  isSelected: boolean;
  isDataIncluded: boolean;
};

type Props = {
  onDoSomething: ({ type, isSelected, isDataIncluded }: FuncProps) => Promise<void>;
};

describe('71625454', () => {
  test('should pass', async () => {
    const onDoSomethingMock: Props['onDoSomething'] = jest.fn(({ type, isSelected, isDataIncluded }: FuncProps) =>
      Promise.resolve()
    );
    await onDoSomethingMock({ type: 'a', isSelected: true, isDataIncluded: false });
    expect(onDoSomethingMock).toBeCalled();
  });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文