Angular SwUpdate Jest测试

fivyi3re  于 2023-01-18  发布在  Jest
关注(0)|答案(1)|浏览(167)

bounty将在5天后过期。此问题的答案可获得+200声望奖励。Developer正在寻找规范答案

我有一个PWA,我想测试,该对话框显示时,有更新重新加载的位置,如果用户同意更新。
下面是我的测试:

describe('AppUpdateDialog', () => {
    let component: AppUpdateDialog;
    let fixture: ComponentFixture<AppUpdateDialog>;

    const dialogMock = {
        close: () => {
            // Empty method for testing
        },
    };

    const swUpdateMock = {
        activateUpdate: () => {
            return Promise.resolve();
        },
    };

    beforeEach(async () => {
        TestBed.configureTestingModule({
            declarations: [AppUpdateDialog],
            imports: [
                MatIconModule,
                RouterTestingModule,
                MatDialogModule,
                ServiceWorkerModule.register('ngsw-worker.js', {
                    enabled: environment.production,
                    registrationStrategy: 'registerImmediately',
                }),
            ],
            providers: [
                {
                    provide: MatDialogRef,
                    useValue: dialogMock,
                },
                { provide: SwUpdate, useValue: swUpdateMock },
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(AppUpdateDialog);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should render correctly', () => {
        expect(fixture).toMatchSnapshot();
    });

    it('should close the dialog', () => {
        jest.spyOn(component.dialogRef, 'close');
        component.onNoClick();
        expect(component.dialogRef.close).toHaveBeenCalled();
    });

    it('should activate update and reload on yes click', async () => {
        const mockReload = jest.fn();
        const mockLocation = { reload: mockReload };
        Object.defineProperty(window, 'location', { value: mockLocation });
        component.onYesClick();
        expect(mockReload).toHaveBeenCalled();
    });
});

所以我的测试在最后一行失败了:
预期呼叫数:〉= 1已接电话数:0
如何正确修复此测试用例?

oknwwptz

oknwwptz1#

这可能是一个解决方案:https://remarkablemark.org/blog/2018/11/17/mock-window-location/

it('should activate update and reload on yes click', () => {
    delete window.location;
    window.location = { reload: jest.fn() };
    component.onYesClick();
    expect(window.location.reload).toHaveBeenCalled();
});

不确定异步,但我认为在这段代码中不需要。

相关问题