Created
January 25, 2021 17:35
-
-
Save zMrKrabz/cdcaaded80fe07bcdc25ce7e5d2289f6 to your computer and use it in GitHub Desktop.
How to mock requests and test functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import nock from "nock"; | |
import "mocha"; | |
import { expect } from "chai"; | |
import got, { ExtendOptions } from "got"; | |
describe("Request Test", () => { | |
// Instead of having our requests visit the acutal API, we mock responses | |
nock("https://api.kanye.rest") | |
.get("/") | |
.reply(200, { quote: "For me giving up is way harder than trying." } ); | |
describe("Sample Got Test", () => { | |
const extendOptions: ExtendOptions = { | |
headers: { | |
"sec-ch-ua": "\"Google Chrome\";v=\"87\", \" Not;A Brand\";v=\"99\", \"Chromium\";v=\"87\"", | |
"accept": "*/*", | |
"dnt": "1", | |
"x-requested-with": "XMLHttpRequest", | |
"sec-ch-ua-mobile": "?0", | |
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36", | |
"origin": "www.snipesusa.com", | |
"sec-fetch-site": "same-origin", | |
"sec-fetch-mode": "cors", | |
"sec-fetch-dest": "empty", | |
"accept-encoding": "gzip, deflate, br", | |
"accept-language": "en-US,en;q=0.9" | |
}, | |
followRedirect: false, | |
}; | |
const client = got.extend(extendOptions); | |
it("should get quote", async function () { | |
try { | |
const resp = await client.get<{ quote: string }>("https://api.kanye.rest", { | |
responseType: "json", | |
}); | |
expect(resp.body).to.deep.equal({ quote: "For me giving up is way harder than trying." }); | |
} catch (err) { | |
console.log(err); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment