'Jest test if React Context called service with params
App
import React from 'react'
import MyComponent from './MyComponent'
import {ConnectionProvider from './context'
const App extends React.Component {
render() {
return (
<ConnectionProvider>
<MyComponent />
</ConnectionProvider>
)
}
}
export default App
Context
import React, { createContext, useState } from 'react'
import { Connection } from '@web/_types'
import { ContactService } from '@web/_services'
interface IConnectionContextData {
connections: Connection[]
getConnections: () => void
connect: (
contactId: string,
source: string,
) => void
}
const ConnectionContextDefaultValue: IConnectionContextData = {
connections: []
getConnections: () => null,
connect: () => null,
}
const useConnectionContextValue = (): ConnectionContextData => {
const [connections, setConnections] = useState<Connection[]>([])
const connect = async (
contactId: string,
source: string
) => {
try {
await ContactService.connectRep(contactId, source)
getConnections()
} catch (error) {
console.log(error)
}
}
const getConnections = async () => {
const getContactsResponse = await UserService.getConnections()
setConnections(getContactsResponse.data)
}
return {
getConnections,
connect,
}
}
export const ConnectionContext = createContext<ConnectionContextData>(
ConnectionContextDefaultValue
)
export const ConnectionProvider: React.FC = ({ children }) => {
return (
<ConnectionContext.Provider value={useConnectionContextValue()}>
{children}
</ConnectionContext.Provider>
)
}
MyComponent
import React, {useContext} from 'react'
import {ConnectionContext} from './context'
const MyComponent extends React.Component {
const { connect } = useContext(ConnectionContext)
render() {
return (
<>
<button onClick={() => connect('1234', 'Some source')}>
Click me
</button>
</>
)
}
}
export default MyComponent
Hopefully, this is enough context (pardon the sh!tty pun).
I'm trying to figure out how to test that ContactService.connectRep was called with contactId and source. Everything I've read says to avoid testing context directly, but I can only mock up connect as jest.fn().
I've mocked the context provider, and I can see that the connect function was called with contactId and source. That all passes just fine, but I'm not sure how to approach knowing how ContactService.connectRep was called. Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
