Concept Flow - Testing async behavior
Start Test
Call async function
Wait for Promise to resolve
Check result
Pass
End Test
The test starts by calling an async function, waits for it to finish, then checks the result to decide pass or fail.
import { ref } from 'vue'; async function fetchData() { return new Promise(resolve => setTimeout(() => resolve('done'), 100)); } const result = ref(''); async function test() { result.value = await fetchData(); }
| Step | Action | Promise State | result.value | Notes |
|---|---|---|---|---|
| 1 | Call test() | pending | '' | test() starts, fetchData() called, promise pending |
| 2 | Await fetchData() | pending | '' | Waiting for promise to resolve |
| 3 | After 100ms, promise resolves | fulfilled | 'done' | fetchData() resolves with 'done' |
| 4 | Assign result.value = 'done' | fulfilled | 'done' | result.value updated after await |
| 5 | Test can check result.value | fulfilled | 'done' | Test sees updated value |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| result.value | '' | '' | '' | 'done' | 'done' | 'done' |
| Promise State | n/a | pending | pending | fulfilled | fulfilled | fulfilled |
Testing async behavior in Vue: - Use async functions and await to handle promises. - Test waits for async calls to finish before checking results. - result.value updates only after await resolves. - Always await async calls in tests to get correct state. - Promises start pending and become fulfilled when done.
await nextTick() after triggering an async update?await nextTick()await nextTick() waits for Vue to complete these DOM updates before assertions.wrapper.text() after the test runs?const wrapper = mount(MyComponent);
await wrapper.find('button').trigger('click');
await nextTick();
test('updates message after async call', async () => {
const wrapper = mount(MyComponent);
wrapper.vm.fetchData();
expect(wrapper.text()).toContain('Loaded');
});test('displays user name after fetch', async () => {
const wrapper = mount(UserComponent);
// What should you do here?
});flushPromises() waits for all pending promises like fetch to finish.await nextTick() ensures DOM updates are applied.Pass the test and this pattern moves unknown