如何测试将use-mobx-react-lite观察器与useContext一起使用的组件?

时间:2019-04-30 09:59:51

标签: reactjs unit-testing mobx mobx-react react-testing-library

我正在尝试将上下文从未经身份验证更改为已身份验证,以便可以测试组件在这两种状态下的行为。 我尝试使用Context测试它。提供程序包装器,但是它不起作用,因为观察者不依赖于Context.Provider,并且组件本身无法将状态更改为已验证。 我还找到了一种解决方案here(code sandbox example),但是它所做的就是在测试文件本身中创建一个新组件,而无需实际测试实际组件。

  • 列表项

6平方米?从嵌入式

import { observer } from 'mobx-react-lite';
import RootStoreContext from '../../stores/RootStore/RootStore';
const Navbar: FunctionComponent = observer(
  (): JSX.Element => {
    const { authStore } = useContext(RootStoreContext);
    return (
      <nav className="navbar ">
        {authStore.authState.isAuth ? (
          <button
            onClick={() => authStore.resetAuthState()}
            data-testid="logout"
          >
            Logout
          </button>
        ) : (
          <>
            <NavLink to="/sign-up" data-testid="login">
              <strong>Sign up</strong>
            </NavLink>
            <NavLink to="/login" data-testid="signup">
              <strong>Login</strong>
            </NavLink>
          </>
        )}
      </nav>
    );
  },
);

export default Navbar;

import Navbar from './Navbar';
import { RootStore } from '../../stores/RootStore/RootStore';
describe('<Navbar />', (): void => {
  const { container, rerender, queryByTestId, getByText } = render(<Navbar />, {
    wrapper: ({ children }) => <BrowserRouter>{children}</BrowserRouter>,
  });

  it('snapshot', (): void => {
    expect(container).toMatchSnapshot();
  });
//Im trying to interact with authState so i can make this test work.
  it('should have Login and SignUp links if isAuth is false', async (): Promise<
    void
  > => {
    const LoginLink = queryByTestId('login');
    const SignUpLink = queryByTestId('signup');
    const LogoutLink = queryByTestId('logout');
    expect(LoginLink).toBeTruthy();
    expect(SignUpLink).toBeTruthy();
    expect(LogoutLink).toBeNull();
  });
  const LoginLink = queryByTestId('login');
    const SignUpLink = queryByTestId('signup');
    const LogoutLink = queryByTestId('logout');
    expect(LoginLink).toBeNull();
    expect(SignUpLink).toBeNull();
    expect(LogoutLink).toBeTruthy();
});

0 个答案:

没有答案