Skip to content

Instantly share code, notes, and snippets.

@zMrKrabz
Created January 25, 2021 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zMrKrabz/cdcaaded80fe07bcdc25ce7e5d2289f6 to your computer and use it in GitHub Desktop.
Save zMrKrabz/cdcaaded80fe07bcdc25ce7e5d2289f6 to your computer and use it in GitHub Desktop.
How to mock requests and test functions
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