问题
I am wanting to write a test for the code below which basically renders all the blog posts such that the latest post is on the top. I am new to React test Library and every time I add my components in the React testing Library I get the following error :
No overload matches this call. Overload 1 of 2, '(props: Readonly): PostList', gave the following error. Property 'posts' is missing in type '{}' but required in type 'Readonly'. Overload 2 of 2, '(props: State, context?: any): PostList', gave the following error. Property 'posts' is missing in type '{}' but required in type 'Readonly'.
Here is my test file
afterEach(cleanup);
it('renders correctly with all my props', () => {
const post = {
Name: 'abc',
title: 'Post title',
}
const {getByPlaceholderText, queryByTestId, debug} = render(
<Notes={notes}/>
);
debug();
});
回答1:
Looking at the Generics typings for your PostList
class component, I noticed that posts
is a required property for its props. Therefore, when you render your component in your tests, you are required to include the required props (posts
). Usually, in unit tests, it will be fine to supply your props with mock data.
const samplePostsData = {
1: {
_id: 1,
fullName: 'abc',
title: 'This is the title',
body: 'Random post created for testing purpose only',
updatedAt: ''
}
};
render(<PostList posts={samplePostsData}/>)
In addition, key needs to be of type string
.
interface State {
posts: {
[key: string]: Post
}
}
来源:https://stackoverflow.com/questions/59973614/writing-test-case-for-rendering-post-list