import { flushSync, mount, unmount } from 'svelte'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import ChangePassword from '$lib/components/ChangePassword.svelte'; import axios from 'axios'; let component; let mocks = vi.hoisted(() => ({ post: vi.fn() })); describe('ChangePassword', () => { beforeEach(() => { vi.mock('axios', async (importActual) => { const actual = await importActual(); const mockAxios = { default: { ...actual.default, create: vi.fn(() => ({ ...actual.default.create(), post: mocks.post })) } }; return mockAxios; }); mocks.post.mockResolvedValue({ status: 200 }); component = mount(ChangePassword, { target: document.body // `document` exists because of jsdom }); flushSync(); }); afterEach(() => { unmount(component); }); test('onsubmit happy path', async () => { // Set value in all three inputs at once: const inputs = document.body.querySelectorAll('input[type=password]'); inputs.value = 'pass'; // Click the button, then flush the changes so you can synchronously write expectations document.body.querySelector('button[type=submit]').click(); flushSync(); // expect(axios.post).toHaveBeenCalledWith('/password', { password: 'pass', to: 'pass' }); expect(Array.from(inputs.values()).map((i) => i.value)).toEqual(['', '', '']); }); });