【问题标题】:JEST test for my component to throw an exception inside useEffectJEST 测试我的组件在 useEffect 中抛出异常
【发布时间】:2020-06-30 14:19:41
【问题描述】:

以下组件有效。但是我想知道如何使用断言来测试它是否会引发错误。

不,它使用上下文为我的项目提供值。但我不确定这是否与这个问题有关,但我还是想添加它。我希望无论组件是否在上下文中,都可以只断言要抛出的错误。

./MyContext.jsx

// ... generic imports left out for brevity
import request from './request';

const MyContext = createContext([{}, () => {}]);

const fetchList = async (url) => request(url);

const MyContextProvider = ({ children }) => {
  const [list, setList] = useState({
    fetchStatus: undefined,
    data: [],
  });

  const apiUrl = 'https://www.example.com/my-api/';

  useEffect(() => {
    setList({ fetchStatus: 'pending' });
    
    fetchList(apiUrl)
      .then((response) => {
        if (!response.success) {
          // 
          // this is what I want to test
          // 
          throw new Error(`The list fetch on ${apiUrl} was not successful.`);
        }
        setList({ data: response, fetchStatus: 'success' });
      })
      .catch(() => {
        setList({ fetchStatus: 'error' });
      });
  }, [apiUrl, setList]);

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

export { MyContext, MyContextProvider };

然后在测试中:

./SomeComponent.spec.js

// ... generic imports left out for brevity
import { MyContext, MyContextProvider } from './MyContext';
import request from './request';

jest.mock('../../../shared/request');

function Wrapper ({children}) {
  return (
    <MyContextProvider>{children}</MyContextProvider>
  )
}

async function setup() {
  let context;
  const TestComponent = () => {
    context = React.useContext(MyContext);
    return '<></>';
  }
  
  await act(async () => {
    render(<TestComponent />, { wrapper: Wrapper });
  });

  return context;
}

// PASS!
it('when request fetch fails it returns with fetchStatus error', async () => {
  const data = { success: false };
  request.mockResolvedValue(data);
  const { readSchedules } = await setup();
  expect(readSchedules).toEqual({ fetchStatus: 'error' });
});

// UNSURE HOW TO TEST FOR THE EXCEPTION TO THROW
it('throws an exception if the request response is invalid', async () => {
  const data = { success: false };
  request.mockResolvedValue(data);
  await setup();

  const error = 'The list fetch on https://www.example.com/my-api/ was not successful.';

  // How should I get this one?
  expect(??).to.throw(Error(error));
});

我希望这能解释我面临的问题。

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

    效果不会抛出错误,而是会处理它。由于catch 不使用捕获的错误,因此不会影响结果。

    应该和不成功的响应一样:

    request.mockRejectedValue(new Error('whatever'));
    await setup();
    const { readSchedules } = await setup();
    expect(readSchedules).toEqual({ fetchStatus: 'error' });
    

    【讨论】:

    • 多哈。我明白你的意思了。在捕获中它应该得到“错误”,然后我应该对此做一些事情......我会检查如何以不同的方式做到这一点。
    • 如果你真的不需要这个错误,没关系。但是您可以将其附加到状态,至少出于调试目的。
    猜你喜欢
    • 2018-02-13
    • 2018-09-11
    • 2020-11-24
    • 2020-06-22
    • 2023-01-25
    • 1970-01-01
    • 2020-08-18
    • 2014-05-10
    相关资源
    最近更新 更多