基本上文件寫得很清楚,所以照著做就差不多。
然後我覺得單元測試可以講很多,這篇簡單帶過一個測試案例。
npm i --save-dev @nuxt/test-utils vitest
.package.json
"scripts": {
...
"test": "vitest",
},
import { describe, it, expect } from 'vitest';
import { productToCartFormatter } from '../../formatter';
import type { ProductDetailModel } from '~/models/apiModel';
import type { cartProductModel } from '~/models/viewModel';
describe('Formatter - productToCartFormatter', () => {
const pModes: ProductDetailModel = {
id: '1',
title: "Essence Mascara Lash Princess",
description: "The Essence Mascara Lash Princess is a popular mascara known for its volumizing and lengthening effects. Achieve dramatic lashes with this long-lasting and cruelty-free formula.",
category: "beauty",
price: 9.99,
discountPercentage: 7.17,
rating: 4.94,
stock: 5,
tags: [
"beauty",
"mascara"
],
brand: "Essence",
sku: "RCH45Q1A",
weight: 2,
dimensions: {
width: 23.17,
height: 14.43,
depth: 28.01
},
warrantyInformation: "1 month warranty",
shippingInformation: "Ships in 1 month",
availabilityStatus: "Low Stock",
reviews: [
{
rating: 2,
comment: "Very unhappy with my purchase!",
date: "2024-05-23T08:56:21.618Z",
reviewerName: "John Doe",
reviewerEmail: "john.doe@x.dummyjson.com"
},
{
rating: 2,
comment: "Not as described!",
date: "2024-05-23T08:56:21.618Z",
reviewerName: "Nolan Gonzalez",
reviewerEmail: "nolan.gonzalez@x.dummyjson.com"
},
{
rating: 5,
comment: "Very satisfied!",
date: "2024-05-23T08:56:21.618Z",
reviewerName: "Scarlett Wright",
reviewerEmail: "scarlett.wright@x.dummyjson.com"
}
],
returnPolicy: "30 days return policy",
minimumOrderQuantity: 24,
meta: {
createdAt: "2024-05-23T08:56:21.618Z",
updatedAt: "2024-05-23T08:56:21.618Z",
barcode: "9164035109868",
qrCode: "https://assets.dummyjson.com/public/qr-code.png"
},
images: [
"https://cdn.dummyjson.com/products/images/beauty/Essence%20Mascara%20Lash%20Princess/1.png"
],
thumbnail: "https://cdn.dummyjson.com/products/images/beauty/Essence%20Mascara%20Lash%20Princess/thumbnail.png"
}
const cModel: cartProductModel = {
"id": "1",
"title": "Essence Mascara Lash Princess",
"price": 9.99,
"stock": 5,
"thumbnail": "https://cdn.dummyjson.com/products/images/beauty/Essence%20Mascara%20Lash%20Princess/thumbnail.png",
"quantity": 1
}
it('Generate cartProductModel successfully', () => {
expect(productToCartFormatter(pModes, 1)).toMatchObject(cModel);
});
});
RERUN tests/formatter/index.test.ts x7
✓ tests/formatter/index.test.ts (1)
✓ Formatter - productToCartFormatter (1)
✓ Generate cartProductModel successfully
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 13:50:24
Duration 37ms
PASS Waiting for file changes...
press h to show help, press q to quit