jest typescript test fetch

March 24th, 2023

example-service.ts

import { OktaAuth } from '@okta/okta-auth-js'

 

 

export interface FooData {

hello: string

}

 

 

export interface FooResult {

success: boolean

extraInfoForFrontend: string

}

 

 

export async function foo(oktaAuth: OktaAuth, data: FooData): Promise<FooResult> {

const accessToken = oktaAuth.getAccessToken()

try {

const response = await fetch("/foo", {

headers: {

Authorization: `Bearer ${accessToken}`,

},

})

 

 

const json = await response.json()

return {

success: true,

extraInfoForFrontend: json.message,

}

} catch (err) {

return {

success: false,

extraInfoForFrontend: 'Could not get data',

}

}

}

 

example-service.test.ts

import { foo } from './example-service'

import { OktaAuth } from '@okta/okta-auth-js'

 

 

const mockedFetchJson = jest.fn()

const mockedFetch = jest.fn(() =>

Promise.resolve({

json: mockedFetchJson,

})

) as any

type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>

global.fetch = mockedFetch as Fetch

 

 

const ACCESS_TOKEN = "foo-access-token"

const oktaAuth = {

getAccessToken: () => ACCESS_TOKEN

} as any as OktaAuth // force typescript to accept it, event though the types don't match

const CONFIG_WITH_AUTH = {

headers: {

Authorization: `Bearer ${ACCESS_TOKEN}`,

},

}

 

 

beforeEach(() => {

mockedFetch.mockClear();

mockedFetchJson.mockClear();

});

 

 

describe('example-service', () => {

 

 

it('should return expected data', async () => {

mockedFetchJson.mockResolvedValue({message: "Message sent."})

 

 

const data = {hello: "foo"}

const response = await foo(oktaAuth, data)

expect(response).toEqual({

success: true,

extraInfoForFrontend: "Message sent."

})

expect(mockedFetch).toHaveBeenCalledTimes(1)

expect(mockedFetch).toHaveBeenCalledWith("/foo", CONFIG_WITH_AUTH)

expect(mockedFetchJson).toHaveBeenCalledTimes(1)

})

 

 

it('should handle failures', async ()=>{

mockedFetch.mockRejectedValue("Some network error occurred")

 

 

const data = {hello: "foo"}

const response = await foo(oktaAuth, data)

expect(response).toEqual({

success: false,

extraInfoForFrontend: "Could not get data"

})

expect(mockedFetch).toHaveBeenCalledTimes(1)

expect(mockedFetch).toHaveBeenCalledWith("/foo", CONFIG_WITH_AUTH)

expect(mockedFetchJson).not.toHaveBeenCalled()

})

})

 

inspiration