【发布时间】:2021-08-22 23:38:24
【问题描述】:
我想测试我的组件:
const Courses: React.FC = () => {
const { data, error } = useSWR(
'some url...',
fetcher
);
console.log(data, error);
if (error) {
return (
<CoursesContainer>
<Error>Something went wrong.</Error>
</CoursesContainer>
);
}
if (!data) return <Loader title="loader" />;
return (
<CoursesContainer>
<CollapsibleTable courses={data} />
</CoursesContainer>
);
};
export default Courses;
但我不知道为什么我不能模拟它为每个测试返回不同的值。我试过了:
jest.mock('../../utils/fetcher', () => ({
fetcher: jest
.fn()
.mockReturnValue('default')
.mockReturnValueOnce('first call')
.mockReturnValueOnce('second call'),
readData: jest.fn(),
}));
test('Basic render. fetch pending', async () => {
const component = render(<Courses />);
await waitFor(() => component.findByTitle('loader'));
expect(component.baseElement).toMatchSnapshot();
});
test('Basic render, fetch success', async () => {
const component = render(<Courses />);
await waitFor(() => component.findByText('CollapsibleTable'));
expect(component.baseElement).toMatchSnapshot();
});
test('Basic render, fetch error', async () => {
const component = render(<Courses />);
await waitFor(() => component.findByText('Something went wrong.'));
expect(component.baseElement).toMatchSnapshot();
});
而且效果不好。对于每个测试,只有 first callconsole.log() - 来自 Courses.tsx 的 console.log(data, error);。
来自jest的反馈:
console.log
undefined undefined
at Courses (src/components/Courses.tsx:14:11)
console.log
first call undefined
at Courses (src/components/Courses.tsx:14:11)
console.log
first call undefined
at Courses (src/components/Courses.tsx:14:11)
console.log
first call undefined
at Courses (src/components/Courses.tsx:14:11)
当然,第三次测试 (Basic render, fetch error) 也因此失败。
我不能改用spyOn(),因为我的fetcher 是没有对象的单独函数。
@@ 更新@@
有我的fetcher 和readData 函数:
const fetcher = (url: string) => {
return fetch(url)
.then((response) => response.json())
.then((data: Array<IFetchData>) => readData(data));
};
const readData = (data: Array<IFetchData>) => {
let myData: Array<ICourse> = [];
[ there are some simple operations which create new myData array with
properties which I need (there is not any async operations)]
return myData;
};
【问题讨论】:
-
fetcher和readData是否返回承诺? -
我刚刚在底部添加了这些函数来提问
-
你无法达到你想要的。请参阅更新的答案。 @poldeeek
标签: javascript reactjs jestjs mocking fetch