JEST 测试我的组件在 useEffect 中抛出异常
JEST test for my component to throw an exception inside useEffect
以下组件有效。但是我想知道如何使用断言来测试它是否会抛出错误。
不,它使用上下文为我的项目提供价值。但我不确定这是否与这个问题相关,但我还是想添加它。我希望无论组件是否在上下文中,都可以只对要抛出的错误进行断言。
./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));
});
我希望这能解释我面临的问题。
效果不会抛出错误但会处理它。由于 catch
不使用捕获的错误,因此不会影响结果。
应该和不成功的回复一样:
request.mockRejectedValue(new Error('whatever'));
await setup();
const { readSchedules } = await setup();
expect(readSchedules).toEqual({ fetchStatus: 'error' });
以下组件有效。但是我想知道如何使用断言来测试它是否会抛出错误。
不,它使用上下文为我的项目提供价值。但我不确定这是否与这个问题相关,但我还是想添加它。我希望无论组件是否在上下文中,都可以只对要抛出的错误进行断言。
./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));
});
我希望这能解释我面临的问题。
效果不会抛出错误但会处理它。由于 catch
不使用捕获的错误,因此不会影响结果。
应该和不成功的回复一样:
request.mockRejectedValue(new Error('whatever'));
await setup();
const { readSchedules } = await setup();
expect(readSchedules).toEqual({ fetchStatus: 'error' });