Reputation: 4874
jest.mock('../redux/storeConfigure', () => () => ({
getState: () => ({ auth: { token: 'TEST_TOKEN' } })
}))
import { prepareRequestHeaders } from './fetch'
describe('prepareRequestHeaders', () => {
it('returns header with Authorization if token is set', () => {
expect(prepareRequestHeaders()['Authorization']).toBe('Bearer TEST_TOKEN')
})
it('returns header without Authorization if token is not set', () => {
?????
})
})
In prepareRequestHeaders
I import ../redux/storeConfigure
How to remock ../redux/storeConfigure
with other implementation?
EDIT:
/* fetch.js */
import { store } from '../app'
export const prepareRequestHeaders = () => {
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
}
const { token } = store.getState().auth
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
return headers
}
/* app.js */
import storeConfigure from './redux/storeConfigure'
export const store = storeConfigure()
/* Directories strucutre */
- redux
- storeConfigure.js
- api
- fetch.js
- api.test.js
app.js
Upvotes: 0
Views: 1443
Reputation: 7449
Something like this should work out:
let mockGetState;
jest.mock('../redux/storeConfigure', () => () => {
mockGetState = jest.fn().mockReturnValue({ auth: { token: 'TEST_TOKEN' } })
return { getState: mockGetState }
})
import { prepareRequestHeaders } from './fetch'
describe('prepareRequestHeaders', () => {
it('returns header with Authorization if token is set', () => {
expect(prepareRequestHeaders()['Authorization']).toBe('Bearer TEST_TOKEN')
})
it('returns header without Authorization if token is not set', () => {
mockGetState.mockReturnValueOnce({auth: {token: 'SOMETHING_ELSE'}})
// make your assertion
})
})
When you assign to a Jest mock (jest.fn()
) you can change its return value whenever you want. The name of it has to start with mock
because of mock hoisting
Upvotes: 2