我的组件:
const Books = ({books, searchField}) => {
const filterBooks = () => {
return books.filter(b => b.name.includes(searchField))
}
return (
<BookList books={filterBooks()}/>
)
}
书单组件:
const BookList = ({books}) => {
return (
books.map(b => {
return<BookCard book={b}/>
})
)
}
BookCard 组件:
const BookCard =(book) => {
return(
<div>
<h2>{book.name}</h2>
<p>{book.price}</p>
</div>
)
}
我需要测试 filterBooks 函数,但由于我使用的是函数式组件,我不能使用 instance()
方法,因为它在函数式组件中返回 null
在类组件中,我可以做到在功能组件中无法实现的:
let wrapper;
beforeEach(() => {
let mockProps = {
books: [],
searchField: ''
}
wrapper = shallow(<Books/>);
})
it('filter Books correctly', () => {
mockProps = {
books: [
{
name: 'ants',
price: '$10'
},
{
name: 'the secret',
price: '$10'
}
],
searchField: 'a'
}
wrapper = shallow(<Books {...mockProps}/>)
expect(wrapper.instance().filterBooks().toEqual([{name: 'ants', price: '$10'}])
})
如何在我的功能组件中实现这一点?
答案 0 :(得分:0)
您可以使用 .find(selector) => ShallowWrapper 查找 BookList
组件浅包装并检查其 books
属性。
例如
Books.js
:
import React from 'react';
import BookList from './BookList';
const Books = ({ books, searchField }) => {
const filterBooks = () => {
return books.filter((b) => b.name.includes(searchField));
};
return <BookList books={filterBooks()} />;
};
export default Books;
BookList.js
:
import React from 'react';
import BookCard from './BookCard';
const BookList = ({ books }) => {
return books.map((b) => {
return <BookCard book={b} />;
});
};
export default BookList;
Books.test.js
:
import React from 'react';
import { shallow } from 'enzyme';
import Books from './Books';
import BookList from './BookList';
describe('66074394', () => {
it('should pass', () => {
const mockProps = {
books: [
{
name: 'ants',
price: '$10',
},
{
name: 'the secret',
price: '$10',
},
],
searchField: 'a',
};
const wrapper = shallow(<Books {...mockProps} />);
expect(wrapper.find(BookList).prop('books')).toEqual([{ name: 'ants', price: '$10' }]);
});
});
单元测试结果:
PASS examples/66074394/Books.test.js
66074394
✓ should pass (6 ms)
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 83.33 | 100 | 50 | 82.35 |
BookCard.js | 75 | 100 | 0 | 75 | 4
BookList.js | 66.67 | 100 | 0 | 66.67 | 5-6
Books.js | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.57 s