Destructure using useContext breaks Jest

Viewed 25

I am using Jest for unit testing and finding that functions I imported using useContext appear to break my Jest.

I am getting this error for example:

TypeError: Cannot destructure property 'loginUser' of '(0 , _react.useContext)(...)' as it is undefined.

This is the test I am running:

test('Login page renders with no errors', () => {
    render(<Router><Login/></Router>)
});

and my jest.config:

module.exports = {
    preset: "ts-jest/presets/js-with-ts",
    transform: {
        '^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/react-scripts/config/jest/babelTransform.js',
        '^.+\\.css$': '<rootDir>/node_modules/react-scripts/config/jest/cssTransform.js',
        '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '<rootDir>/node_modules/react-scripts/config/jest/fileTransform.js',
        "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest-amcharts",
        "\\.[jt]sx?$": "babel-jest",
        "^.+\\.css$": "jest-transform-css",
        "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest",
    },
    transformIgnorePatterns: [
//      '[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$',
        '^.+\\.module\\.(css|sass|scss)$',
        "[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$",
        "/node_modules/(?!react-file-drop)",
        "node_modules/(?!variables/.*)"
    ],
    moduleNameMapper: {
        '^react-native$': 'react-native-web',
        '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
        "\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/mocks/fileMock.js",
        "\\.(css|less)$": "<rootDir>/mocks/fileMock.js",
        "^.+\\.(css|less|scss)$": "babel-jest",
    },
    moduleDirectories: ["node_modules", "src"],
}

This is my implementation of loginUser:

const loginUser = async (tokens) => {
    let response = await axios.post('http://127.0.0.1:8000/api/token/',tokens)
    try {
        setAuthTokens(authTokens => ({
            ...response.data
        }))
        const decoded = jwt_decode(response.data.access)
        setUser(user => ({
            ...decoded
        }))            localStorage.setItem('authTokens',JSON.stringify(response.data))
        history.push('/')
    }
    catch(err) {
        alert(response.data.user);
    }
}

Any help would be greatly appreciated

0 Answers
Related