Skip to content

Commit

Permalink
test: clean up tests' console logging (#2211)
Browse files Browse the repository at this point in the history
* chore: clean up tests' console output

* fix: lazy state tests were broken

* chore: clean up tests' console output
  • Loading branch information
markwhitfeld authored Aug 22, 2024
1 parent 77cf50d commit 1c1e589
Show file tree
Hide file tree
Showing 17 changed files with 166 additions and 122 deletions.
22 changes: 12 additions & 10 deletions integration/app/app.component[observable].spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { AppComponent } from './app.component';
import { Pizza } from './store/todos/todos.model';
import { TodosState } from './store/todos/todos.state';
import { TodoState } from './store/todos/todo/todo.state';
import { skipConsoleLogging } from '@ngxs/store/internals/testing';

describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
Expand Down Expand Up @@ -46,18 +47,19 @@ describe('AppComponent', () => {
expect(todos.length).toEqual(2);
});

it('should remove a todo', async () => {
// Arrange & act
component.addTodo('Get Milk');
component.addTodo('Clean Bathroom');
component.removeTodo(1);
it('should remove a todo', () =>
skipConsoleLogging(async () => {
// Arrange & act
component.addTodo('Get Milk');
component.addTodo('Clean Bathroom');
component.removeTodo(1);

const todos = await firstValueFrom(component.todos$);
const todos = await firstValueFrom(component.todos$);

// Assert
expect(todos.length).toBe(1);
expect(todos[0]).toBe('Get Milk');
});
// Assert
expect(todos.length).toBe(1);
expect(todos[0]).toBe('Get Milk');
}));

it('should set toppings using form control', async () => {
// Arrange
Expand Down
19 changes: 11 additions & 8 deletions integration/app/app.component[signal].spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { AppComponent } from './app.component';
import { Pizza } from './store/todos/todos.model';
import { TodosState } from './store/todos/todos.state';
import { TodoState } from './store/todos/todo/todo.state';
import { skipConsoleLogging } from '@ngxs/store/internals/testing';

describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
Expand Down Expand Up @@ -41,15 +42,17 @@ describe('AppComponent', () => {
expect(component.todos().length).toEqual(2);
});

it('should remove a todo', async () => {
component.addTodo('Get Milk');
component.addTodo('Clean Bathroom');
component.removeTodo(1);
it('should remove a todo', () =>
skipConsoleLogging(async () => {
component.addTodo('Get Milk');
component.addTodo('Clean Bathroom');

const todos = component.todos();
expect(todos.length).toEqual(1);
expect(todos[0]).toEqual('Get Milk');
});
component.removeTodo(1);

const todos = component.todos();
expect(todos.length).toEqual(1);
expect(todos[0]).toEqual('Get Milk');
}));

it('should set toppings using form control', async () => {
fixture.detectChanges();
Expand Down
16 changes: 9 additions & 7 deletions packages/logger-plugin/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ module.exports = {
displayName: 'logger-plugin',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/test-setup.ts'],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$'
}
},
globals: {},
coverageDirectory: '../../coverage/packages/logger-plugin',
transform: {
'^.+\\.(ts|js|html)$': 'jest-preset-angular'
'^.+\\.(ts|mjs|js|html)$': [
'jest-preset-angular',
{
isolatedModules: true,
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$'
}
]
},
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
Expand Down
2 changes: 2 additions & 0 deletions packages/logger-plugin/tests/issues/issue-1551.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { InitState, State } from '@ngxs/store';

import { setupWithLogger, LoggerSpy, formatActionCallStack } from '../helpers';
import { Injectable } from '@angular/core';

describe('https://github.com/ngxs/store/issues/1551', () => {
class RemoveTodo {
Expand All @@ -20,6 +21,7 @@ describe('https://github.com/ngxs/store/issues/1551', () => {
name: 'test',
defaults: stateModelDefaults
})
@Injectable()
class TodosState {}

it('should not filter out numbers', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/storage-plugin/tests/storage-for-feature.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ describe('forFeature', () => {
'should log an error if the `keys` property is set to `*`',
freshPlatform(async () => {
// Arrange
const spy = jest.spyOn(console, 'error');
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});

const appConfig = setupAppConfig({
keys: '*'
Expand All @@ -117,6 +118,7 @@ describe('forFeature', () => {
);
} finally {
spy.mockRestore();
logSpy.mockRestore();
}
})
);
Expand Down
28 changes: 15 additions & 13 deletions packages/store/experimental/tests/preboot-wait-stable.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
provideStore,
select
} from '@ngxs/store';
import { freshPlatform } from '@ngxs/store/internals/testing';
import { freshPlatform, skipConsoleLogging } from '@ngxs/store/internals/testing';
import { withExperimentalNgxsPendingTasks } from '@ngxs/store/experimental';

describe('preboot feature + stable', () => {
Expand Down Expand Up @@ -62,19 +62,21 @@ describe('preboot feature + stable', () => {
'should wait for app to become stable',
freshPlatform(async () => {
// Arrange
const html = await renderApplication(
() =>
bootstrapApplication(TestComponent, {
providers: [
provideExperimentalZonelessChangeDetection(),
const html = await skipConsoleLogging(() =>
renderApplication(
() =>
bootstrapApplication(TestComponent, {
providers: [
provideExperimentalZonelessChangeDetection(),

provideStore([CountriesState], withExperimentalNgxsPendingTasks())
]
}),
{
document: '<app-root></app-root>',
url: '/'
}
provideStore([CountriesState], withExperimentalNgxsPendingTasks())
]
}),
{
document: '<app-root></app-root>',
url: '/'
}
)
);

// Assert
Expand Down
17 changes: 10 additions & 7 deletions packages/store/internals/testing/src/ngxs.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { NgxsModule, Store } from '@ngxs/store';

import { NgxsTestModule } from './helpers/ngxs-test.module';
import { NgxsOptionsTesting, NgxsTesting } from './symbol';
import { skipConsoleLogging } from './skip-console-logging';

export class NgxsTestBed {
public static configureTestingStates(options: NgxsOptionsTesting): NgxsTesting {
Expand All @@ -19,13 +20,15 @@ export class NgxsTestBed {
options.before();
}

TestBed.configureTestingModule({
imports: [
NgxsTestModule,
NgxsModule.forRoot(options.states || [], options.ngxsOptions || {}),
...(options.imports || [])
]
}).compileComponents();
skipConsoleLogging(() =>
TestBed.configureTestingModule({
imports: [
NgxsTestModule,
NgxsModule.forRoot(options.states || [], options.ngxsOptions || {}),
...(options.imports || [])
]
}).compileComponents()
);

NgxsTestBed.ngxsBootstrap();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ describe('DispatchOutsideZoneNgxsExecutionStrategy', () => {

// Act
const spy = jest.spyOn(console, 'warn').mockImplementation();
const logSpy = jest.spyOn(console, 'log').mockImplementation();

await platformBrowserDynamic().bootstrapModule(MockModule, { ngZone: 'noop' });

Expand All @@ -336,6 +337,7 @@ describe('DispatchOutsideZoneNgxsExecutionStrategy', () => {
expect(spy).toHaveBeenCalledWith(getZoneWarningMessage());
} finally {
spy.mockRestore();
logSpy.mockRestore();
}
})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
NoopNgxsExecutionStrategy,
Selector
} from '@ngxs/store';
import { freshPlatform } from '@ngxs/store/internals/testing';
import { freshPlatform, skipConsoleLogging } from '@ngxs/store/internals/testing';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

Expand Down Expand Up @@ -127,9 +127,11 @@ describe('NoopNgxsExecutionStrategy', () => {
class TestModule {}

// Act
const { injector } = await platformBrowserDynamic().bootstrapModule(TestModule, {
ngZone: 'noop'
});
const { injector } = await skipConsoleLogging(() =>
platformBrowserDynamic().bootstrapModule(TestModule, {
ngZone: 'noop'
})
);

// Assert
try {
Expand Down
10 changes: 5 additions & 5 deletions packages/store/tests/helpers/counter.state.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { State, Action, Selector } from '../../src/public_api';
import { State, Action, Selector, StateContext } from '../../src/public_api';
import { Injectable } from '@angular/core';

export class Increment {
Expand Down Expand Up @@ -32,12 +32,12 @@ export class CounterState {
constructor(private math: MathService) {}

@Action(Increment)
increment(state: number) {
return this.math.add(state, 1);
increment(ctx: StateContext<number>) {
ctx.setState(state => this.math.add(state, 1));
}

@Action(Decrement)
decrement(state: number) {
return this.math.subtract(state, 1);
decrement(ctx: StateContext<number>) {
ctx.setState(state => this.math.subtract(state, 1));
}
}
12 changes: 7 additions & 5 deletions packages/store/tests/helpers/todo.state.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core';
import { State, Action, Selector } from '../../src/public_api';
import { State, Action, Selector, StateContext } from '../../src/public_api';

export class AddTodo {
static readonly type = 'ADD_TODO';
Expand All @@ -24,12 +24,14 @@ export class TodoState {
}

@Action(AddTodo)
addTodo(state: string[], action: AddTodo) {
return [action.todo, ...state];
addTodo(ctx: StateContext<string[]>, action: AddTodo) {
const state = ctx.getState();
ctx.setState([action.todo, ...state]);
}

@Action(RemoveTodo)
removeTodo(state: string[], action: RemoveTodo) {
return state.filter((_, index) => index !== action.index);
removeTodo(ctx: StateContext<string[]>, action: RemoveTodo) {
const state = ctx.getState();
ctx.setState(state.filter((_, index) => index !== action.index));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -138,17 +138,19 @@ describe('State per signal', () => {
'should server-side render the content correctly even if the dispatch is untracked',
freshPlatform(async () => {
// Arrange
const html = await renderApplication(
() =>
bootstrapApplication(TestComponent, {
providers: [
provideExperimentalZonelessChangeDetection(),
provideStore([NumberState], withExperimentalNgxsPendingTasks())
]
}),
{
document: '<app-root></app-root>'
}
const html = await skipConsoleLogging(() =>
renderApplication(
() =>
bootstrapApplication(TestComponent, {
providers: [
provideExperimentalZonelessChangeDetection(),
provideStore([NumberState], withExperimentalNgxsPendingTasks())
]
}),
{
document: '<app-root></app-root>'
}
)
);

// Assert
Expand Down
Loading

0 comments on commit 1c1e589

Please sign in to comment.