iT邦幫忙

2023 iThome 鐵人賽

DAY 17
0
Modern Web

由前向後,從前端邁向全端系列 第 17

17.【從前端到全端,Nextjs+Nestjs】加入測試

  • 分享至 

  • xImage
  •  

文章重點

  • 設定Jest
  • 加入元件和元件生成器測試

本文

今天我們來為我們的Nextjs App和component來添加測試。我們先使用已經建立好的Jest和Playwright進行測試。

我們先試著執行。

pnpm exec nx run-many --target=test

https://ithelp.ithome.com.tw/upload/images/20231003/20108931ogZxqFpdks.png
修正一下generator的測試

import { componentGenerator } from "./generator";
import { ComponentGeneratorSchema } from "./schema";
import { Tree, addProjectConfiguration, readProjectConfiguration } from "@nx/devkit";
import { createTreeWithEmptyWorkspace } from "@nx/devkit/testing";

describe("component generator", () => {
	let tree: Tree;
	const options: ComponentGeneratorSchema = { name: "test", componentName: "SampleComponent" };

	beforeEach(() => {
		tree = createTreeWithEmptyWorkspace();
		addLibToWorkspace(tree, options.name);
	});

	it("should run successfully", async () => {
		await componentGenerator(tree, options);
		const config = readProjectConfiguration(tree, options.name);
		expect(config).toBeDefined();

		const componentPath = tree.exists(`libs/${options.name}/src/lib/${options.componentName}`);
		expect(componentPath).toBeTruthy();
	});
});

function addLibToWorkspace(tree: Tree, libName: string) {
	addProjectConfiguration(tree, libName, {
		root: `libs/${libName}`,
		sourceRoot: `libs/${libName}/src`,
		projectType: "library",
		targets: {},
		tags: []
	});
}

https://ithelp.ithome.com.tw/upload/images/20231003/201089316z7w8M0Sgn.png

在我們開始為我們的元件添加測試前,先設置測試環境。這包括安裝必要的依賴,並在 tsconfig.base.json 和 jest.setupTest.ts 中進行相應的配置。通過這些設置來確保了測試環境的正確設置

安裝常用的依賴

pnpm add -D @testing-library/user-event @testing-library/dom @testing-library/jest-dom @types/testing-library__jest-dom

我們知道Jest是一個廣泛使用的測試框架。然而,當涉及到 DOM 操作和驗證時,Jest本身可能不足以處理所有的狀態行為。所以我們需要加入jest-dom這個lib,jest-dom是一個為 Jest 提供自定義匹配器的,使得在測試中驗證 DOM 狀態變得更容易直觀。接下來我們進行設置

首先在tsconfig.base.json添加types設置:

		// ...
		"types": ["node", "jest", "@testing-library/jest-dom"]
	},
	"exclude": ["node_modules", "tmp"]
}

創建設定檔案在根目錄jest.setupTest.ts:

import "@testing-library/jest-dom";

打開根目錄上的jest,jest.preset.js:

const nxPreset = require("@nx/jest/preset").default;

module.exports = {
	...nxPreset,
	setupFilesAfterEnv: ["./jest.setupTest.ts"],
	testEnvironment: "jest-environment-jsdom"
};

接下來打開我們的libs\iron-components\tsconfig.spec.json並在types中加入@testing-library/jest-dom

{
	"extends": "./tsconfig.json",
	"compilerOptions": {
		"outDir": "../../dist/out-tsc",
		"module": "commonjs",
		"types": ["jest", "node", "@testing-library/jest-dom"]
	},
	"include": [
		"jest.config.ts",
		"src/**/*.test.ts",
		"src/**/*.spec.ts",
		"src/**/*.test.tsx",
		"src/**/*.spec.tsx",
		"src/**/*.test.js",
		"src/**/*.spec.js",
		"src/**/*.test.jsx",
		"src/**/*.spec.jsx",
		"src/**/*.d.ts"
	]
}

執行:

pnpm exec nx run iron-components:test --watch=true 

現在我們開始為我們的元件添加測試:
稍微修正我們的libs\iron-components\src\lib\AuthForm\AuthForm.tsx加入id和htmlFor
https://ithelp.ithome.com.tw/upload/images/20231003/201089315tYswpPr3O.png
接著加入測試libs\iron-components\src\lib\AuthForm\AuthForm.spec.tsx:

import { fireEvent, render, screen } from "@testing-library/react";
import AuthForm from "./AuthForm";

describe("AuthForm", () => {
	it("should render successfully", () => {
		const { baseElement } = render(<AuthForm />);
		expect(baseElement).toBeTruthy();
	});

	it("should render login form by default", () => {
		render(<AuthForm />);
		expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
		expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
		expect(screen.queryByLabelText(/確認密碼/i)).not.toBeInTheDocument();
	});

	it("should switch to register form on button click", () => {
		render(<AuthForm />);
		fireEvent.click(screen.getByText(/沒有帳戶?點擊註冊/i));
		expect(screen.getByLabelText(/確認密碼/i)).toBeInTheDocument();
	});
});

https://ithelp.ithome.com.tw/upload/images/20231003/201089310CjKRfZpQQ.png


總結

通過本文,我們了解了如何添加測試。並且我們配置了 Jest 設置,並進行了初始的測試運行。然後,我們編寫了元件生成器的測試,以確保它能夠正確生成所需的元件。


上一篇
16.【從前端到全端,Nextjs+Nestjs】使用Mock來模擬GraphQL
下一篇
18.【從前端到全端,Nextjs+Nestjs】加入測試(二)
系列文
由前向後,從前端邁向全端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言