// SCRIPT.JS
// const fetch = require("node-fetch")
// Was originally called here but is now called in the test
const getPeople = (fetch) => {
return fetch("https://swapi.dev/api/people")
.then(res => res.json())
.then(data => {
return {
count: data.count,
results: data.results
}
}).catch(err => err)
}
const isCity = (city, db) => {
return db.includes(city)
// Returns truthy or falsy
}
module.exports = {
getPeople,
isCity
}
// SCRIPT.TEST.JS (that is a naming convention: file-name.test.js)
// Destructuring
const {getPeople, isCity} = require("./script")
const fetch = require("node-fetch")
test("calls swapi to get people with a promise", () => {
expect.assertions(2)
return getPeople(fetch)
.then(data => {
expect(data.count).toEqual(82)
expect(data.count).not.toEqual(42)
})
})
//Capture calls
test("testing captured calls", () => {
const mock = jest.fn()
let result = mock("foo")
expect(mock).toHaveBeenCalled()
expect(mock).toHaveBeenCalledTimes(1)
expect(mock).toHaveBeenCalledWith("foo")
})
// Set return values
test("mock return value", () => {
const mock = jest.fn()
mock.mockReturnValue("bar")
expect(mock("foo")).toBe("bar")
expect(mock).toHaveBeenCalledWith("foo")
})
// Replace implementation of dependency (in this case, node-fetch)
test("test getPeople with dependency injection", () => {
const mockFetch = jest.fn()
.mockReturnValue(Promise.resolve({
json: () => Promise.resolve({
count: 87,
results: [1,2,3,4,5]
})
}))
expect.assertions(5)
return getPeople(mockFetch).then(data => {
expect(mockFetch.mock.calls.length).toEqual(1)
expect(mockFetch).toHaveBeenCalled()
expect(mockFetch).toHaveBeenCalledTimes(1)
expect(mockFetch).toHaveBeenCalledWith("https://swapi.dev/api/people")
expect(data.count).toEqual(87)
})
})
let db = []
const initDb = () => db = ["Vienna", "London", "San Juan", "Medllin"]
const closeDb = () => db = []
// To init before each and close after each
beforeEach(() => initDb())
afterEach(() => closeDb())
beforeAll(() => initDb())
afterAll(() => closeDb())
test("city db has Vienna", () => {
expect(isCity("Vienna", db)).toBeTruthy()
})
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter