Skip to content

bug(MatSnackBar): snackbar duration does not work in tests when there is no component #22065

@catfireparty

Description

@catfireparty

Reproduction

Repro repo -> https://github.com/jdpearce/snack-test

Basically:

@Injectable({
  providedIn: 'root',
})
export class SnackbarService {
  constructor(private snackbar: MatSnackBar) {}

  open(): void {
    const ref = this.snackbar.open('This is a snackbar', 'Dismiss', {
      duration: 1000,
    });

    ref.onAction().subscribe(() => {
      console.log('snackbar dismissed with action');
    });
  }
}

and:

describe('snackbar service', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [MatSnackBarModule, NoopAnimationsModule],
      providers: [SnackbarService],
    }).compileComponents();
  });

  it('should load the snackbar on and go away after 1 second', (done) => {
    const service = TestBed.inject(SnackbarService);

    expect(document.querySelector('simple-snack-bar')).toBeFalsy();

    service.open();

    expect(document.querySelector('simple-snack-bar')).toBeTruthy();

    setTimeout(() => {
      expect(document.querySelector('simple-snack-bar')).toBeFalsy('oh dear');
      done();
    }, 1000);
  });
});

(please forgive the setTimeouts, I tried doing this with fakeAsync as well but that doesn't work either)

Steps to reproduce:

  1. ng test

Note that when the there is a component under test (app.component.spec.ts) everything works as expected, but in snackbar.service.spec.ts the snackbar doesn't go away.

Expected Behavior

I expect duration to be paid attention to when the snackbar is instantiated in a service under test.

Actual Behavior

The snackbar just sits there at the top of the screen until manually dismissed.

Screenshot 2021-03-01 at 13 07 03

Environment

  • Angular: 11.2.3
  • CDK/Material: 11.2.2
  • Browser(s): Chrome, FireFox
  • Operating System (e.g. Windows, macOS, Ubuntu): macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: material/snack-barneeds investigationA member of the team needs to do further investigation to determine the root cause

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions