简体   繁体   中英

ReactJS: Undefined Error: How to define isAuthorized() and logonID from authContext in spec.js test file?

The app seems to be working fine.

In my search js class I have:

import AuthContext from ../context/userAuthContext;
const authContext = useContext(UserAuthContext);

I have references to logonID, and isAuthorized(), when I run the spec.js test file, some tests fail saying these are undefined. I am not sure why... how can I define them in the test file? I think that is the issue... but I'm not sure... or is it an issue with how I am referencing them?

console.log(authContext.authResponse.logonID) // console log shows a test id
console.log(authContext.isAuthorized()) //console log shows true

So it seems these statements are returning accurate values. This is why I assume it is just an issue in the test file. Let me know if this is not enough info.

Help or advice please, thank you!


//authContext

import React from "react";

const UserAuthContext = React.createContext();

export const UserAuthContextProvider = ({
  children,
  authResponse,
  userManager,
}) => {
  const value = {
    authResponse: authResponse,
    userManager,
    getAuthToken: async function () {
      try {
        let value = await this.userManager.getUser();
        return `Bearer ${value.access_token}`;
      } catch (exp) {
        return null;
      }
    },

    getLogonID: function () {
      return this.authResponse?.logonID
        ? this.authResponse?.logonID
        : undefined;
    },
    getUserRoles: function () {
      return this.authResponse?.userGroups
        ? this.authResponse?.userGroups
        : [];
    },
    isAuthorized: function () {
      return this.getUserRoles().some(
        (element) => element === "authorized_access_role"
      );
    },
  };

  return (
    <UserAuthContext.Provider value={value}>
      {children}
    </UserAuthContext.Provider>
  );
};

export default UserAuthContext;

//snippets from the test file

beforeEach(() => {
  wrapper = mount(
    <UserAuthContext.Provider
      value={{
        isAuthorized: jest.fn(() => true),
        getLogonID: jest.fn(() => logonID),
      }}
    >
      <ViewDataRouter
        setHeaderTitle={setHeaderTitle}
        location={{}}
        history={history}
      />
    </UserAuthContext.Provider>
  );
  userId = wrapper.find("input[name='userId']");
  userNumber = wrapper.find("input[name='userNumber']");


//example test scenario which leads to undefined error in the search class
it("should test Search button is disabled by default", () => {
  expect(wrapper.find("button[name='searchUserNumber']").prop("disabled")).toBe(
    true
  );
});

Your context provider does not take in isAuthorized or getLogonID from your value prop so it is not doing anything with the jest.fn() you're passing from your tests.

Instead of passing in functions to the context provider, It does look like it takes in userManager and AuthRepsonse -- so I would mock the functions in userManager and provide the expected authResponse to the provider instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM