Svelte:如何使用 jest 监视模板中指定的函数?

Sco*_*ale 5 javascript jestjs svelte testing-library

我有一个 Svelte 组件,它导入一个函数,然后将该函数提供为模板中的单击处理程序。我想使用玩笑来监视和模拟这个函数。模拟该函数后,对调用模拟函数的函数的任何调用都会按预期工作,但单击使用该函数作为处理程序的元素会导致调用实际函数而不是模拟函数。A

这是一个存在问题的codesandbox https://codesandbox.io/s/crazy-fast-uxgqe?file=/app.test.js

test-util.ts
export const foo = () => console.log('real foo');
export const bar = () => foo();
Run Code Online (Sandbox Code Playgroud)
Test.svelte
<script lang="ts">
    import { foo, bar } from '@utils/test-util';
</script>

<button on:click={foo} data-testid="foo">foo</button>
<button on:click={bar} data-testid="bar">bar</button>
Run Code Online (Sandbox Code Playgroud)
import { render } from '@testing-library/svelte';
import Test from '@components/Test.svelte';
import * as testUtil from '@utils/test-util';
import userEvent from '@testing-library/user-event';

test('fails', async () => {
  const fooMock = jest
    .spyOn(testUtil, 'foo')
    .mockImplementation(() => console.log('mock foo'));
  const testComponent = render(Test);
  await userEvent.click(testComponent.getByTestId('bar')); // logs 'mock foo'
  await userEvent.click(testComponent.getByTestId('foo')); // logs 'real foo'
  expect(fooMock).toHaveBeenCalledTimes(2); // fails, actual value 1
});
Run Code Online (Sandbox Code Playgroud)

如果只是为了测试而添加像 bar 这样的中间函数,我将如何模拟 foo 以便在用作处理程序时调用模拟?