Skip to content

Instantly share code, notes, and snippets.

@rainerhahnekamp
Last active September 7, 2023 12:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rainerhahnekamp/d4a7bb6efdaf68eb4bd25b4cb17da7eb to your computer and use it in GitHub Desktop.
Save rainerhahnekamp/d4a7bb6efdaf68eb4bd25b4cb17da7eb to your computer and use it in GitHub Desktop.
Angular Unit Tests with effect()
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