|
1 |
| -import { Component, input, signal } from '@angular/core' |
| 1 | +import { Component, Injectable, inject, input, signal } from '@angular/core' |
2 | 2 | import { TestBed } from '@angular/core/testing'
|
3 | 3 | import { describe, expect, vi } from 'vitest'
|
4 | 4 | import { By } from '@angular/platform-browser'
|
@@ -453,4 +453,45 @@ describe('injectMutation', () => {
|
453 | 453 |
|
454 | 454 | await expect(() => mutateAsync()).rejects.toThrowError(err)
|
455 | 455 | })
|
| 456 | + |
| 457 | + test('should execute callback in injection context', async () => { |
| 458 | + const errorSpy = vi.fn() |
| 459 | + @Injectable() |
| 460 | + class FakeService { |
| 461 | + updateData(name: string) { |
| 462 | + return Promise.resolve(name) |
| 463 | + } |
| 464 | + } |
| 465 | + |
| 466 | + @Component({ |
| 467 | + selector: 'app-fake', |
| 468 | + template: ``, |
| 469 | + standalone: true, |
| 470 | + providers: [FakeService], |
| 471 | + }) |
| 472 | + class FakeComponent { |
| 473 | + mutation = injectMutation(() => { |
| 474 | + try { |
| 475 | + const service = inject(FakeService) |
| 476 | + return { |
| 477 | + mutationFn: (name: string) => service.updateData(name), |
| 478 | + } |
| 479 | + } catch (e) { |
| 480 | + errorSpy(e) |
| 481 | + throw e |
| 482 | + } |
| 483 | + }) |
| 484 | + } |
| 485 | + |
| 486 | + const fixture = TestBed.createComponent(FakeComponent) |
| 487 | + fixture.detectChanges() |
| 488 | + |
| 489 | + // check if injection contexts persist in a different task |
| 490 | + await new Promise<void>((resolve) => queueMicrotask(() => resolve())) |
| 491 | + |
| 492 | + expect( |
| 493 | + await fixture.componentInstance.mutation.mutateAsync('test'), |
| 494 | + ).toEqual('test') |
| 495 | + expect(errorSpy).not.toHaveBeenCalled() |
| 496 | + }) |
456 | 497 | })
|
0 commit comments