Search code examples
angularkarma-jasminengrxngrx-effects

SnackBar at effect spec file


I'm trying to test my effect spec file. I'm using matSnackBar in the effect file. when I run it, the _snackbar is declared as undefined and then the tests field. this is what i tried to do :

describe('InquiryWizardEffects', () => {
let actions: Observable<any>;
let effects: InquiryWizardEffects;
let inquiryService: MockInquiryService;
let _snackBar: MatSnackBar;

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            NxModule.forRoot(),
            StoreModule.forRoot({}),
            EffectsModule.forRoot([]),
            MatSnackBarModule,
        ],
        providers: [
            InquiryWizardEffects,
            DataPersistence,
            provideMockActions(() => actions),
            { provide: InquiriesService, useClass: MockInquiryService },
            { provide: MatSnackBar}
        ]
    });
    _snackBar= TestBed.get(MatSnackBar);
    effects = TestBed.get(InquiryWizardEffects);
    inquiryService = TestBed.get(InquiriesService);
});

What am I doing wrong?

Edit

this is the error that i got :

'Cannot read property 'openFromComponent' of undefined '

it comes when i am doing :

this._snackBar.openFromComponent(CreatedEntitySnackBarComponent, {
            duration:  environment.longDurationSnackBar,
            panelClass: [style],
            horizontalPosition: 'right',
            data: {
                title: title,
                entityId: entityId
            }
        });
    }

Solution

  • You can use "useValue" to provide the SnackBar and fake it.

    describe('InquiryWizardEffects', () => {
    let actions: Observable<any>;
    let effects: InquiryWizardEffects;
    let inquiryService: MockInquiryService;
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                NxModule.forRoot(),
                StoreModule.forRoot({}),
                EffectsModule.forRoot([]),
                MatSnackBarModule,
            ],
            providers: [
                InquiryWizardEffects,
                DataPersistence,
                provideMockActions(() => actions),
                { provide: InquiriesService, useClass: MockInquiryService },
                { provide: MatSnackBar, useVale: {openFromComponent: (param1, param2) => { return; }}},
            ]
        });
        effects = TestBed.get(InquiryWizardEffects);
        inquiryService = TestBed.get(InquiriesService);
    });
    

    Try if this works.