Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
これ。【Jest x redux-thunk x GraphQL x TypeScript】test example

【Jest x redux-thunk x TypeScript】 test example

I was looking for an example. Just a little less,

so leave what you actually wrote.

This is different from the official.

The place where Youre is written is domain knowledge,

so please be aware

import * as Redux from 'redux'
import * as Operations from '../operations'
import * as Actions from '../actions'
import * as Store from 'path/store'

import * as GraphqlTypes from 'path/types/gen/api'
import * as MemberRegisterEntity from 'path/domain/your/entity'
import * as MockStore from 'path/__test__/mockdata/store'
import * as MockData from './mockData'
import * as ExtraArgMock from 'path/store/__test__/extraArgMock'

let dispatch: jest.Mock // type as jest Mock
let getState: jest.Mock // ...
let mockCtx: Store.ThunkExtraArg // type ThunkExtraArg,as thunk function 3th argument
let fun: jest.Mock // if you pass some function to operation or value, you can defined here



describe('your', () => {
////////////Preparation////////////////////
    beforeEach(async () => {
        dispatch = jest.fn()
        getState = jest.fn()
        mockCtx = Redux.compose(
            ExtraArgMock.appendApi(
                new ExtraArgMock.MockApiClient(
                    MockData.YourQueryResponse,
                    MockData.YourMutationResponse
                )
            )
        )(ExtraArgMock.defaultValue())
        errors = {}
        getState.mockReturnValue(MockStore.store.getState()) // MockStore is MockData Store
    })
////////////////////////////////
    it('not call query when has error', async () => {
        fun = jest.fn()
        await Operations.register(
            MockData.data,
            MockData.errors,
        )(dispatch, getState, mockCtx)
        expect(mockCtx.api.mutate).toBeCalledTimes(0)
    })
    it('call query', async () => {
        await Operations.your( // thunk function
            MockData.data,
            errors,
        )(dispatch, getState, mockCtx)
    ///////////////////////////////////////
// Now that the operation has been performed, you test how it was performed

        expect(mockCtx.api.mutate).toHaveBeenCalledWith( // Arguments passed when called
            new GraphqlTypes.CreateYourMutationRequest({
                your: [MockData.data]
            })
        )
        expect(resetForm.mock.calls.length).toBe(1) // Function executed when called
        expect(dispatch.mock.calls.length).toBe(3) // Dispatch times executed when called
        expect(dispatch).toHaveBeenLastCalledWith({ // last Dispatch executed action when called
            // Action.close
            type: 'toplayer/your/yourRegister/close'
        })
    })
})

Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment