NextAuth.js 模擬

用於 jest、storybook 等的 NextAuth.js 模擬供應器。

在 Github 上檢視

next-auth-mock

安裝

將此函式庫加入您的 devDependencies 來安裝

pnpm add --save-dev @tomfreudenberg/next-auth-mock

Storybook

新增至您的 storybook 預覽

更新 .storybook/main.js 並附加到您的擴充功能清單

module.exports = {
  addons: ['@tomfreudenberg/next-auth-mock/storybook']
}

使用工具列選單

重新啟動 storybook 後,工具列中會出現一個額外的圖示

可讓您選取工作階段狀態。

撰寫 stories 並包含您的元件

// ./stories/pages/denied.stories.jsx

import DeniedPage from '@/pages/auth/denied';

export default {
  title: 'Pages/Auth',
  component: DeniedPage
};

export const DeniedPageStory = (args) => <DeniedPage />;

DeniedPageStory.parameters = {};

您現在可以透過工具列項目來控制和測試 useSession() 的元件狀態

next-auth-mock-storybook-preview

使用固定的狀態來測試元件

為確保您的元件可以使用固定的驗證狀態進行測試,無論工具列選取為何,您可以使用 stories 中的參數來覆寫工作階段屬性

// /stories/pages/signin.stories.jsx

import SigninPage from '@/pages/auth/signin';

export default {
  title: 'Pages/Auth',
  component: SigninPage
};

export const SigninPageStory = (props) => <SigninPage />;

SigninPageStory.parameters = {
  nextAuthMock: {
    session: 'unknown'
  }
};

以上程式碼會載入由 id unknown 定義的工作階段設定。您也可以定義完整的工作階段物件,例如

SigninPageStory.parameters = {
  nextAuthMock: {
    session: {
      data: {
        id: 999,
        login: 'user',
        role: 'user',
        roles: ['user'],
        username: 'User',
        email: 'user@local'
      },
      status: 'unauthenticated'
    }
  }
};

在 stories 中存取目前的工作階段資料

如果您在使用工作階段值時需要變更 stories 程式碼,您可以透過 useSession hook 存取這些值。

import { useSession } from 'next-auth/react';

export const MyStory = (props) => {
  // get access to current session data
  const session = useSession();

  ...

自訂工作階段驗證狀態

此元件帶來一組預設的驗證狀態:unknownloadingadminadminAutheduseruserAuthed

/**
 *
 * default items for toolbar menu to select different auth-states while mocking
 *
 */
export const mockAuthStates = {
  unknown: {
    title: 'session unknown',
    session: null
  },
  loading: {
    title: 'session loading',
    session: {
      data: null,
      status: 'loading'
    }
  },
  admin: {
    title: 'admin not authenticated',
    session: {
      data: {
        id: 1,
        login: 'admin',
        role: 'admin',
        roles: ['admin', 'user'],
        username: 'Administrator',
        email: 'admin@local'
      },
      status: 'unauthenticated'
    }
  },
  adminAuthed: {
    title: 'admin authenticated',
    session: {
      data: {
        id: 1,
        login: 'admin',
        role: 'admin',
        roles: ['admin', 'user'],
        username: 'Administrator',
        email: 'admin@local'
      },
      status: 'authenticated'
    }
  },
  user: {
    title: 'user not authenticated',
    session: {
      data: {
        id: 999,
        login: 'user',
        role: 'user',
        roles: ['user'],
        username: 'User',
        email: 'user@local'
      },
      status: 'unauthenticated'
    }
  },
  userAuthed: {
    title: 'user authenticated',
    session: {
      data: {
        id: 999,
        login: 'user',
        role: 'user',
        roles: ['user'],
        username: 'User',
        email: 'user@local'
      },
      status: 'authenticated'
    }
  }
};

您可以完全或部分變更此設定以符合您的需求。因此,您可以在本機資料夾中建立名為 .storybook/previewMockAuthStates.js 的檔案,並為 webpack 定義別名。

更新 .storybook/main.js

module.exports = {
  addons: ['@tomfreudenberg/next-auth-mock/storybook'],
  webpackFinal: async (config) => {
    config.resolve.alias['@tomfreudenberg/next-auth-mock/storybook/preview-mock-auth-states'] = path.resolve(__dirname, 'previewMockAuthStates.js');
  }
};

現在,Webpack 會為 previewMockAuthStates 設定載入您的檔案 .storybook/previewMockAuthStates.js

只要複製預設狀態即可
const defaultMockAuthStates = require('@tomfreudenberg/next-auth-mock').mockAuthStates;

module.exports = defaultMockAuthStates;
變更部分狀態
const defaultMockAuthStates = require('@tomfreudenberg/next-auth-mock').mockAuthStates;

module.exports = {
  ...defaultMockAuthStates,
  admin: {
    title: 'My Admin unauthenticated',
    session: {
      data: {
        id: 777,
        field: 'Additional session field'
      }
    }
  }
}
只需您自己的狀態
module.exports = {
  state0: {
    title: 'State zero',
    session: null
  },
  state1: {
    title: 'A State',
    session: {
      data: {
        id: 1,
        user: 'What you like'
      }
    }
  }
}

自訂工具列圖示和項目

工具列項目也可以完全變更。為此,您需要在 preview.js 中手動實作裝飾器,並將選項設定為您想要的 mockAuthPreviewToolbarItem()。注意:在這種情況下,請勿將元件新增至擴充功能。

更新 .storybook/preview.js

import { mockAuthPreviewToolbarItem, withMockAuth } from '@tomfreudenberg/next-auth-mock/storybook';
import { previewMockAuthStates } from '@tomfreudenberg/next-auth-mock/storybook/preview-mock-auth-states';

export const globalTypes = {
  ...mockAuthPreviewToolbarItem({
    description: 'Auswahl Anmeldestatus',
    defaultValue = null,
    icon = 'user',
    items = previewMockAuthStates
  })
};

export const decorators = [withMockAuth];

Jest

撰寫測試並包含您的元件

// ./tests/pages/signout.stories.jsx

import { render, screen } from '@testing-library/react'
import { withMockAuth } from '@tomfreudenberg/next-auth-mock/jest';
import SignoutPage from '@/pages/auth/signout';

describe('Pages', () => {
  describe('Signout', () => {
    it('should render want to sign out', () => {
      render(withMockAuth(<SignoutPage />, 'userAuthed'));
      expect(screen.getByText('Do you want to sign out?'));
    });
    it('should render not signed in', () => {
      render(withMockAuth(<SignoutPage />, 'unknown'));
      expect(screen.getByText('You are not signed in!'));
    });
  });
});

您可以輸入 mockAuthStates 項目的名稱作為 withMockAuth 的引數,或放入工作階段物件。

import { mockAuthStates } from '@tomfreudenberg/next-auth-mock';
render(withMockAuth(<SignoutPage />, mockAuthStates.userAuthed.session));

// is equal to

render(withMockAuth(<SignoutPage />, 'userAuthed'));

有效的狀態為:unknownloadingadminadminAutheduseruserAuthed

貢獻

如果您想為 next-auth-mock 套件貢獻,或需要從來源使用它,您必須安裝 devDependencies 並建置 dist 套件。

直接前往

git clone git@github.com:TomFreudenberg/next-auth-mock.git

cd next-auth-mock

pnpm install

pnpm build

歡迎您的想法和 PR。

npm 套件

您可以在 npmjs.com 上尋找、使用和下載 npm 套件。

npm 版本  

文件

專案首頁 - 您可以在 Github 找到 README

作者與貢獻

作者:Tom Freudenberg

Copyright (c) 2022 Tom Freudenberg,在 MIT 授權下發佈

由以下人員製作
  • tom-freudenberg
    tom-freudenberg
適用於
    React
標籤