Skip to content

Instantly share code, notes, and snippets.

@Israel025
Created April 25, 2019 02:17
Show Gist options
  • Save Israel025/fa6883e0669756236b2ff4e418df6eca to your computer and use it in GitHub Desktop.
Save Israel025/fa6883e0669756236b2ff4e418df6eca to your computer and use it in GitHub Desktop.
Writing functions and Tests
const axios = require('axios');
async function catFacts() {
try {
const response = await axios({
method: "get",
status: 200,
url: "https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=3"
});
let extracts = response.data;
console.log(`\nBelow are some few random cat facts: \n=============================`);
extracts.forEach(element => {
console.log(`\t ${element.text}\n`)
});
} catch (error) {
let errResponse = {
status: 503,
message: `${error} occured, while trying to connect to the server`
}
return (errResponse);
}
};
module.exports = catFacts;
// console.log(catFacts());
const axios = require("axios");
const getCatFacts = require("../catFacts");
jest.mock('axios');
test('should some facts about cats', () => {
const facts = [
{fact: "The Bombay cat breed was developed to resemble a miniature panther"},
{fact: "Every year, nearly four million cats are eaten in China as a delicacy"},
{fact: "Cats respond better to women than to men, probably due to the fact that women's voices have a higher pitch"}
];
const resp = {data: facts};
axios.get.mockImplementation(() => Promise.resolve(resp))
return getCatFacts().then(resp => expect(resp.data).toEqual(facts));
});
function emailGenerator (firstname, lastname){
let first = String(firstname);
let last = String(lastname);
let letters = /^[A-Za-z]+$/;
if(first.match(letters) && last.match(letters)){
return (`${firstname.toLowerCase()}.${lastname.toLowerCase()}@mailer.com`);
}
return (`Your Firstname and Lastname should contain only letters`);
}
module.exports = emailGenerator;
const mailGen = require("../emailGenerator");
test('uses firstname and lastname to generate email', () => {
expect(mailGen("Mike", "Edward")).toBe("mike.edward@mailer.com");
});
function intArray (intList){
if(!Array.isArray(intList) || intList.length > 0){
let multiList = [];
for(let i = 0; i < intList.length; i++){
if(isNaN(parseInt(intList[i]))){
return `Array of integers only allowed`;
}
multiList.push(intList[i] * 2);
}
return multiList;
}else{
return `Entry must be an Array and must not be empty`;
}
};
module.exports = intArray;
// console.log(intArray([2,3,0,9]));
const multiList = require("../intArray");
test("Multiplies all the item in a number array by 2", () => {
expect(multiList([1])).toEqual([2]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment