Skip to content

Commit

Permalink
Merge pull request #26 from oaknational/feat/check-fetch-ability
Browse files Browse the repository at this point in the history
feat: add fn that sends a fetch req - CON-666
  • Loading branch information
shobbsd authored May 16, 2024
2 parents 01caf33 + 81b973a commit a2fe0fe
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/reportToSlack/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { createSlackReport } from "./index";

describe("createSlackReport", () => {
it("should send a report to Slack", async () => {
const slackUrl = "https://slack.com/api/chat.postMessage";
const message = "Test message";
const additionalInfo = { key: "value" };

// Mock the fetch function
const mockFetch = jest.fn().mockResolvedValue({
ok: true,
json: jest.fn().mockResolvedValue({ success: true }),
});
global.fetch = mockFetch;

const reportToSlack = createSlackReport(slackUrl);
await reportToSlack(message, additionalInfo);

expect(mockFetch).toHaveBeenCalledWith(slackUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
blocks: [
{
type: "section",
text: {
type: "plain_text",
text: message,
emoji: true,
},
},
{
type: "rich_text",
elements: [
{
type: "rich_text_preformatted",
elements: [
{
type: "text",
text: additionalInfo,
},
],
},
],
},
],
}),
});
});

it("should throw an error if sending report to Slack fails", async () => {
const slackUrl = "https://slack.com/api/chat.postMessage";
const message = "Test message";
const additionalInfo = { key: "value" };

// Mock the fetch function to simulate a failed request
const mockFetch = jest.fn().mockResolvedValue({
ok: false,
status: 500,
text: jest.fn().mockResolvedValue("Internal Server Error"),
});
global.fetch = mockFetch;

const reportToSlack = createSlackReport(slackUrl);

await expect(reportToSlack(message, additionalInfo)).rejects.toThrow(
"Failed to send report to Slack: 500 Internal Server Error"
);
});
});
44 changes: 44 additions & 0 deletions src/reportToSlack/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
export const createSlackReport = (slackUrl: string) => {
return async (message: string, additionalInfo: Record<string, unknown>) => {
const res = await fetch(slackUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
blocks: [
{
type: "section",
text: {
type: "plain_text",
text: message,
emoji: true,
},
},
{
type: "rich_text",
elements: [
{
type: "rich_text_preformatted",
elements: [
{
type: "text",
text: additionalInfo,
},
],
},
],
},
],
}),
});

if (!res.ok) {
throw new Error(
`Failed to send report to Slack: ${res.status} ${await res.text()}`
);
}

return res.json();
};
};

0 comments on commit a2fe0fe

Please sign in to comment.