Last active
September 7, 2023 12:44
-
-
Save rainerhahnekamp/d4a7bb6efdaf68eb4bd25b4cb17da7eb to your computer and use it in GitHub Desktop.
Angular Unit Tests with effect()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, effect, signal } from '@angular/core'; | |
import { TestBed } from '@angular/core/testing'; | |
it('does not execute effects', () => { | |
TestBed.runInInjectionContext(() => { | |
let sum = 0; | |
const numbers = signal([1, 2, 3]); | |
effect(() => (sum = numbers().reduce((n1, n2) => n1 + n2))); | |
expect(sum).toBe(6); // 0 | |
numbers.mutate((value) => value.push(4)); | |
expect(sum).toBe(10); // 0 | |
}); | |
}); | |
export const testEffects = | |
(testFn: (runEffects: () => void) => void): (() => void) => | |
() => { | |
const fixture = TestBed.configureTestingModule({ | |
imports: [TestComponent], | |
}).createComponent(TestComponent); | |
TestBed.runInInjectionContext(() => testFn(() => fixture.detectChanges())); | |
}; | |
@Component({ | |
template: '', | |
standalone: true, | |
}) | |
class TestComponent {} | |
it( | |
'should execute effects', | |
testEffects((runEffects) => { | |
let sum = 0; | |
const numbers = signal([1, 2, 3]); | |
effect(() => (sum = numbers().reduce((n1, n2) => n1 + n2))); | |
runEffects(); | |
expect(sum).toBe(6); // 6 | |
numbers.mutate((value) => value.push(4)); | |
runEffects(); | |
expect(sum).toBe(10); // 10 | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment