【问题标题】:how to test a 'redirect' in Nuxt's middleware?如何在 Nuxt 的中间件中测试“重定向”?
【发布时间】:2022-07-28 16:58:02
【问题描述】:

如果中间件中的条件失败,我有一个 nuxt 页面会重定向用户,我想测试是否发生了重定向。

  middleware({ $featureFlag, store, route, redirect }) {
    if (!$featureFlag.isFeatureEnabled()) {
      redirect(`/gfdgfd`);
    }
  },

但是,测试失败:

  it('Should redirect to homepage when FT is turned off', () => {
    const $featureFlag = { track: jest.fn(), isFeatureEnabled: () => false };
    const redirect = jest.fn();
    shallowMount(page, {
      store,
      redirect,
      mocks: {
        $route: { query: { token: {} } },
        $auth: { checkSession: jest.fn() },
        $featureFlag,
      },
      methods: {
        getTokenPayload() {
          return {};
        },
      },
    });
    expect(redirect).toBeCalled(); // THIS FAILS saying 'redirect' was called zero times
  });

【问题讨论】:

    标签: vue.js jestjs nuxt.js vue-test-utils


    【解决方案1】:

    你可以这样试试:

    import { describe, expect, it } from 'vitest';
    import { setup, fetch } from '@nuxt/test-utils';
    
    describe('GET /dashboard', async () => {
        await setup({});
    
        it('redirects to /login because not authenticated', async () => {
            const { headers } = await fetch('/dashboard', { redirect: 'manual' });
            expect(headers.get('location')).toEqual('/login');
        });
    });
    

    在此处查找更多示例:https://github.com/nuxt/framework/blob/main/test/basic.test.ts

    【讨论】:

      猜你喜欢
      • 2021-04-14
      • 2021-06-21
      • 2018-12-16
      • 2021-10-21
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2019-05-21
      相关资源
      最近更新 更多