Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Created October 14, 2022 13:38
Show Gist options
  • Save audunolsen/21bc9500a8fced94c014413d8f72edc6 to your computer and use it in GitHub Desktop.
Save audunolsen/21bc9500a8fced94c014413d8f72edc6 to your computer and use it in GitHub Desktop.
/* eslint-disable prettier/prettier */
// type Input = { code : ErrorMessageKind } | { code: 'illegalWeekday', weekday?: string }
// code: 'illegalEmailDomain', email: string, allowedDomains: string[]
type ErrorMessageKind = "networkError" | "generalError" | 'illegalWeekday'
interface Message {
NO: string
EN: string
}
class GeneralError implements Message {
NO = 'En feil har intruffet'
EN = 'An error has ocurred'
}
class NetworkError implements Message {
NO = 'En nettverksfeil har inntruffet'
EN = 'A Network error has occured'
}
class IllegalWeekday implements Message {
EN = 'Illegal weekday'
NO = 'Ulovlig ukedag'
constructor(day?: string) {
if (!day) return
this.EN = `'${day}' er ulovlig`
this.NO = `'${day}' is illegal`
}
}
type Input = { code: ErrorMessageKind, weekday?: string }
describe("messages", () => {
it("translates a message in english", () => {
expect(translateMessage({ code: "generalError" }, "EN")).toBe("An error has ocurred");
});
it("translates a message in norwegain", () => {
expect(translateMessage({ code: "generalError" }, "NO")).toBe(
"En feil har intruffet"
);
});
it("Expext a network error", () => {
expect(translateMessage({ code: "networkError" }, "NO")).toBe("En nettverksfeil har inntruffet")
})
it("Shows a message with argument", () => {
expect(translateMessage({ code: "illegalWeekday", weekday: 'Doomsday' }, "NO")).toBe("'Doomsday' is illegal")
})
it("Shows a message with argument", () => {
expect(translateMessage({ code: "illegalWeekday", weekday: 'Payday' }, "NO")).toBe("'Payday' is illegal")
})
// it("Shows a message with more array arguments", () => {
// expect(translateMessage({ code: "illegalEmailDomain", email: 'Payday' }, "NO")).toBe("'Payday' is illegal")
// })
});
function translateMessage(kind: Input, locale: "EN" | 'NO') {
const ErrorKind = ({
"networkError": NetworkError,
"generalError": GeneralError,
"illegalWeekday": IllegalWeekday
})[kind.code]
return new ErrorKind(kind.weekday)[locale]
}
@audunolsen
Copy link
Author

audunolsen commented Oct 14, 2022

WIP from a workshop regarding testing for error handling. Had an idea w/ classes that turned out kinda nice, so keeping it here for reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment