Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1.10.0 #11

Merged
merged 3 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "msw-sp",
"version": "1.9.0",
"version": "1.10.0",
"description": "MSW handlers for mocking SharePoint REST api.",
"main": "lib/index.js",
"engines": {
Expand Down
25 changes: 24 additions & 1 deletion src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,10 @@ export const handlers = (options: Tenant | { tenant: Tenant, delay?: DelayMode |
const site = info.params.site?.toString() || "/";
return response(await tenantMock.sites.getSite(site).rootWeb.defaultDocumentLibrary.rootFolder.get(), info);
}),
...get("/_api/web/defaultDocumentLibrary/getitems", async (info) => {
const site = info.params.site?.toString() || "/";
return response(await tenantMock.sites.getSite(site).rootWeb.defaultDocumentLibrary.items.get(), info);
}),
...get("/_api/web/EffectiveBasePermissions", async (info) => {
const site = info.params.site?.toString() || "/";
return response(await tenantMock.sites.getSite(site).rootWeb.effectiveBasePermissions.get(), info);
Expand Down Expand Up @@ -376,9 +380,28 @@ export const handlers = (options: Tenant | { tenant: Tenant, delay?: DelayMode |
...post("/_api/web/lists/getByTitle\\(':title'\\)/items", async (info) => {
const site = info.params.site?.toString() || "/";
const title = info.params.title.toString();
const payload = info.request.json();
const payload = await info.request.json();
return response(await tenantMock.sites.getSite(site).rootWeb.lists.getByTitle(title).items.post(payload), info);
}),
...post("/_api/web/lists/getByTitle\\(':title'\\)/items\\(:id\\)", async (info) => {
const site = info.params.site?.toString() || "/";
const title = info.params.title.toString();
const id = info.params.id.toString();

if (info.request.headers.get("x-http-method") === "DELETE") {
return response(await tenantMock.sites.getSite(site).rootWeb.lists.getByTitle(title).items.getById(id).delete(), info);
}

const payload = await info.request.json();
return response(await tenantMock.sites.getSite(site).rootWeb.lists.getByTitle(title).items.getById(id).post(payload), info);
}),
...post("/_api/web/lists/getByTitle\\(':title'\\)/items\\(:id\\)/validateupdatelistitem", async (info) => {
const site = info.params.site?.toString() || "/";
const title = info.params.title.toString();
const id = info.params.id.toString();
const payload = await info.request.json();
return response(await tenantMock.sites.getSite(site).rootWeb.lists.getByTitle(title).items.getById(id).validateUpdateListItem(payload), info);
}),
...post("/_api/*", async (...params) => {
return response(new Response(undefined, { status: 501, statusText: "Not Implemented (POST)" }), ...params);
}),
Expand Down
60 changes: 58 additions & 2 deletions src/mocks/ItemMock.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { DefaultBodyType } from "msw";
import { BasePermissionsMock } from "./BasePermissionsMock.js";

/**
* @internal
*/
export class ItemMock {

constructor(private item?: Record<string, any>) {
constructor(private items?: Array<Record<string, any>>, private item?: Record<string, any>) {
}

public get effectiveBasePermissions() {
Expand All @@ -27,4 +27,60 @@ export class ItemMock {
{ status: 200 },
);
};

post = async (payload: DefaultBodyType) => {
if (!this.item) {
return new Response(undefined, { status: 404 });
}

Object.assign(this.item, payload);

return new Response(
JSON.stringify({}),
{ status: 200 },
);
};

delete = async () => {
if (!this.item) {
return new Response(undefined, { status: 404 });
}

const index = this.items?.findIndex(i => i.Id === this.item!.Id);
this.item = undefined;
if (index !== undefined) {
this.items?.splice(index, 1);
}

return new Response(
JSON.stringify({}),
{ status: 200 },
);
};

validateUpdateListItem = async (payload: DefaultBodyType) => {
if (!this.item) {
return new Response(undefined, { status: 404 });
}

const obj = payload as {
formValues: Array<{
FieldName: string,
FieldValue: string
}>,
bNewDocumentUpdate?: boolean
};

obj.formValues.reduce((a, b) => {
a[b.FieldName] = b.FieldValue;
return a;
}, this.item);

return new Response(
JSON.stringify({}),
{
status: 200,
},
);
};
}
9 changes: 5 additions & 4 deletions src/mocks/ItemsMock.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { DefaultBodyType } from "msw";
import { ItemMock } from "./ItemMock.js";

/**
Expand All @@ -9,21 +10,21 @@ export class ItemsMock {

getById = (id: number | string) => {
if (!id.toString()) {
return new ItemMock(undefined);
return new ItemMock(this.items, undefined);
}
const item = this.items?.find(item =>
item.Id?.toString() === id.toString() ||
item.ID?.toString() === id.toString());

return new ItemMock(item);
return new ItemMock(this.items, item);
};

get = async () => {
if (!this.items) {
return new Response(undefined, { status: 404 });
}

const mocks = this.items.map(item => new ItemMock(item));
const mocks = this.items.map(item => new ItemMock(this.items, item));
const infos = new Array<any>();
for (let i = 0; i !== mocks.length; i++) {
const list = await mocks[i].get();
Expand All @@ -36,7 +37,7 @@ export class ItemsMock {
);
};

post = async (payload: any) => {
post = async (payload: DefaultBodyType) => {
let ids = this.items?.map(i => i.Id).filter(i => i).map(i => Number.parseInt(i));
if (!ids || ids.length === 0) {
ids = [0];
Expand Down
3 changes: 1 addition & 2 deletions src/mocks/WebMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { BasePermissionsMock } from "./BasePermissionsMock.js";
import { ListMock } from "./ListMock.js";
import { ListsMock } from "./ListsMock.js";
import { UsersMock } from "./UsersMock.js";

type Parent<P, T> = T & { parent?: P };
import type { Parent } from "./types/Parent.js";

/**
* @internal
Expand Down
4 changes: 4 additions & 0 deletions src/mocks/types/Parent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/**
* @internal
*/
export type Parent<P, T> = T & { parent?: P };
94 changes: 94 additions & 0 deletions src/tests/items.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { SPFx, spfi } from "@pnp/sp";
import "@pnp/sp/items/index.js";
import "@pnp/sp/lists/index.js";
import "@pnp/sp/site-users/index.js";
import "@pnp/sp/sites/index.js";
import "@pnp/sp/webs/index.js";
import { setupServer } from 'msw/node';
import * as assert from "node:assert";
import { describe, test } from "node:test";
import { handlers } from '../handlers.js';

void describe("items", async () => {
const url = "https://tenant.sharepoint.com";
const server = setupServer(...handlers({
title: "tenant",
url,
sites: {
"items": {
rootWeb: {
title: "Items Site",
serverRelativeUrl: "/sites/items",
lists: [
{
title: "List",
baseTemplate: 100,
url: "lists/list",
items: [
],
created: "2023-03-21T11:21:08Z",
},
],
},
},
},
}));
server.listen();

const getContext = (serverRelativeUrl: string) => {
return {
pageContext: {
web: {
absoluteUrl: `${url}${serverRelativeUrl}`,
},
legacyPageContext: {
formDigestTimeoutSeconds: 60,
formDigestValue: "digest",
},
},
};
};

await test("crud", async () => {
const sp = spfi().using(SPFx(getContext("/sites/items")));

const list = sp.web.lists.getByTitle("List");

let items = await list.items();
assert.equal(items.length, 0);

// Add
await list.items.add({ Title: "New" });

items = await list.items();
assert.equal(items.length, 1);
assert.equal(items[0].Id, 1);
assert.equal(items[0].Title, "New");

// Update
await list.items.getById(items[0].Id).update({ Title: "New update" });

items = await list.items();
assert.equal(items.length, 1);
assert.equal(items[0].Title, "New update");

// ValidateUpdateListItem
const formValues = [
{
FieldName: "Title",
FieldValue: `New validateUpdateListItem`,
},
];
await list.items.getById(items[0].Id).validateUpdateListItem(formValues);

items = await list.items();
assert.equal(items.length, 1);
assert.equal(items[0].Title, "New validateUpdateListItem");

// Delete
await list.items.getById(items[0].Id).delete();

items = await list.items();
assert.equal(items.length, 0);
});
});