react-adal icon indicating copy to clipboard operation
react-adal copied to clipboard

Unable to mock for test

Open ergunp opened this issue 6 years ago • 4 comments

Hi,

I am trying to mock adalFetch but with no luck. I keep getting, { message: 'User login is required', msg: 'login required' } here is what I have so far

  jest.mock('./../config/adal-config', () => ({
            authContext: () => jest.fn(),
            getToken: () => jest.fn(),
            adalApiFetch: () => Promise.resolve({ json: () => mockedReturnedData }), 
            adalFetch: () => jest.fn() 
          }));

Any help would be greatly appreciated.

ergunp avatar Jan 15 '20 13:01 ergunp

Hi @ergunp You're likely missing one of the functions that you need to mock, however that's just a guess Here's the mock I've generated to be able to test. react-adal.js file in/src/__mocks__dir.

I've set the mockup Azure AD response in mockupPayload

import jwt from 'jsonwebtoken';

const mockupPayload = {
…
};

const generateToken = () => jwt.sign(mockupPayload, 'secret');
const withAdalLogin = () => null;
const adalFetch = () => null;
const runWithAdal = jest.fn((auth, callback) => callback());

class AuthenticationContext {
    getCachedToken = () => generateToken();
    getCachedUser = () => ({
        userName: ‘[email protected]',
        profile: mockupPayload,
    });
}

export { AuthenticationContext, adalFetch, withAdalLogin, runWithAdal };

J-theGit avatar Jan 21 '20 11:01 J-theGit

@J-theGit Thanks I'll give this a shot

ergunp avatar Jan 21 '20 11:01 ergunp

Actually found a better way

await act(async () => {
 jest.spyOn(adalConf, 'adalApiFetch').mockImplementation(() => Promise.resolve({ json: () => existingChange }));
 });

ergunp avatar Jan 23 '20 14:01 ergunp

I'm currently stuck on the same error message using testing-library. How did you resolve this issue?

krytical avatar Jan 26 '22 19:01 krytical