Last active
February 7, 2018 06:05
-
-
Save faceyspacey/3d34849cba929767f1bd8f2a2222c7f0 to your computer and use it in GitHub Desktop.
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
// src/getHeadlines.js | |
export default () => { | |
// do stuff | |
} | |
// __tests__/myTest.js | |
import getHeadlines from '../src/getHeadlines' | |
jest.mock('../src/getHeadlines', () => (user, type) => ({ // notice that the mocked function is the return of an initial function | |
data: [user, type, 'misc'] | |
}) | |
// and here's a version if the function you want to mock isn't the default export | |
// src/getHeadlines.js | |
export const getHeadlines () => { | |
// do stuff | |
} | |
// __tests__/myTest.js | |
import { getHeadlines } from '../src/getHeadlines' | |
jest.mock('../src/getHeadlines', () => ({ // here the return of the initial function is an object representing all the exports in the module | |
getHeadlines: (user, type) => ({ | |
data: [user, type, 'misc'] | |
}) | |
})) | |
it('should return headlines by type', async ()=>{ | |
const headlines = await getHeadlines('abc','xyz'); // your function is async so it should be treated as such in the test | |
expect(headlines.data.length).toBe(3); | |
expect(headlines.data[0]).toEqual('abc') | |
expect(headlines.data[1]).toEqual('xyz') | |
expect(headlines.data[2]).toEqual('misc') | |
}) | |
// note if you wanted we could make the mocked `getHeadlines` async as well like this: | |
jest.mock('../src/getHeadlines', () => ({ | |
getHeadlines: async (user, type) => { | |
await fakeDelay() | |
return [user, type, 'misc'] | |
} | |
})) | |
const fakeDelay = () => new Promise((resolve, reject) => setTimeout(resolve, 10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment