一个类似 jQuery 的 API,用于测试 React 元素和渲染的组件。
teaspoon will not be updated to support React v16+. As of the recent release of enzyme v3, the differences between it and teaspoon have shrunk to almost complete API parity (baring a few things), Given that enzyme is more widely used and maintained it makes sense to switch to that going forward rather than continute to maintain teaspoon and it's underlying pieces. Thanks for using teaspoon ya'll!
Just the right amount of abstraction for writing clear, and concise React component tests.
Table of Contents generated with DocToc
$.selector => selector (alias: $.s)$.dom(instance) => HTMLElement$.compileSelector(selector) => (node) => bool$.defaultContext(context: ?object) => (node) => bool$.fn.length$.fn.unwrap() => Element|Instance|HTMLElement$.fn.get() => Array (alias: toArray())$.fn.tap() => function(Collection)$.fn.end() => Collection$.fn.each(Function iteratorFn)$.fn.map(Function iteratorFn)$.fn.reduce(Function iteratorFn, [initialValue]) -> Collection$.fn.reduceRight(Function iteratorFn) -> Collection$.fn.some(Function iteratorFn) -> bool$.fn.every(Function iteratorFn) -> bool$.instance.fn.dom -> HTMLElement$.fn.find(selector)$.fn.filter(selector)$.fn.is(selector) -> Bool$.fn.children([selector])$.fn.parent([selector])$.fn.parents([selector])$.fn.closest([selector])$.fn.first([selector])$.fn.last([selector])$.fn.only()$.fn.single(selector)$.fn.any([selector])$.fn.none([selector])$.fn.text()To get started install teaspoon via npm:
npm i --save-dev teaspoonTeaspoon is test environment agnostic, so you can (and should) bring your own test runner and frameworks. If you plan on doing normal component rendering (not just shallow rendering) you will also need a DOM environment, whether that's a browser, headless browser, or jsdom.
Like jQuery teaspoon exports a function that creates a collection of nodes; except in this case you select React elements instead of DOM nodes.
import $ from 'teaspoon';
let $div = $(
;
let instance = ReactDOM.render(, mountNode)
let $instance = $(instance);
$instance.find('strong').text() // "John"That's nice but a bit verbose, luckily teaspoon lets you switch between both collection types (element and instance) nice and succinctly.
let Greeting = props =>
;
// renders `` into the DOM and returns an collection of instances
let $elements = $().render();
$elements.find('strong').text() // "John"
$elements.unmount() // removes the mounted component and returns a collection of elements
//or with shallow rendering
$elements.shallowRender()
.find('strong').text() // "John"The supported selector syntax is subset of standard css selectors:
.foodiv[propName="hi"] or div[boolProp]>: direct descendant div > .foo+: adjacent sibling selector~: general sibling selector:has(): parent selector div:has(a.foo):not(): negation:first-child:last-child:text matches "text" (renderable) nodes, which may be a non string value (like a number):dom matches only DOM components:composite matches composite (user defined) components:contains(some text) matches nodes that have a text node descendant containing the provided text:textContent(some text) matches whose text content matches the provided textSelector support is derived from the underlying selector engine: bill. New minor versions of bill are released independent of teaspoon, so you can always check there to see what is supported on the cutting edge.
Unlike normal css selectors, React elements and components often have prop values, and component types that are
not serializable to a string; components are often best selected by their actual class and not a name, and
prop values can complex objects such as a date prop equaling new Date().
For components, we've already seen that you can use the function name or the displayName, but
sometimes they aren't available. A less brittle approach is to select by the function itself. You can
use a tagged template string.
via the $.selector (also aliased as $.s) function for writing complex selectors like so:
$.s`div > ${Greeting}`
// select components with `start` props _strictly_ equal to `min`
let min = 10
$.s`[start=${min}]`If you don't want to use the newer syntax you can also call the selector function directly like:
$.s('div > ', Greeting, '.foo') // equivalent to: $.s`div > ${Greeting}.foo`Use can use these complex selectors in any place a selector is allowed:
let Name = props => {props.name};
let Time = props => {props.date.toLocaleString()}
let Greeting = props =>
;
let now = new Date();
let $inst = $();
$inst
.render()
.find($.s`${Greeting} > strong`)
.text()
$inst
.shallowRender()
.find($.s`${Time}[date=${now}]`)
.only() As far as testing libraries go teaspoon has fairly few opinions about how to do stuff, so you can adapt whatever
testing practices and patterns you like. However there are some patterns and paths that fall out naturally from
teaspoon's API.
tap()tap() provides a way to quickly step in the middle of a chain of queries and
collections to make a quick assertion. Below we quickly make a few changes to the component props and
check that the rendered output is what we'd expect.
let Greeting = props =>
;
$()
.render()
.tap(collection => {
collection
.first('div > :text')
.unwrap()
.should.equal('hello rikki-tikki-tavi')
})
.props('name', 'Nagaina')
.tap(collection => {
collection
.first('div > :text')
.unwrap()
.should.equal('hello Nagaina')
})
.unmount()An age old struggle with testing HTML output is that tests are usually not very resilient to DOM structure changes. You may move a save button into (or out of) some div that your test used to find the button, breaking the test. A classic technique to avoid this is the just use css classes, however it can be hard to distinguish between styling classes, and testing hooks.
In a React environment we can do one better, adding test specific attribute. This is a pattern taken up by libraries like
react-test-tree, and while teaspoon doesn't specifically "support"
that style of selection, its selector engine is more than powerful enough to allow that pattern of querying.
You can choose any prop name you like, but we recommend picking one that isn't likely to collide with a
component's "real" props. In this example let's use _testID.
let Greeting = props =>
;
$()
.render()
.find('[_testID=name]')
.text()
.should.equal('Betty')You can adapt and expand this pattern however your team likes, maybe just using the single testing prop or a few. You can also add some helper methods or pseudo selectors to help codify enforce your teams testing conventions.
Teaspoon has a few conditional requires in order to support versions of React across major versions. This tends to
mean webpack warns about missing files, even when they aren't actually bugs. You can ignore the warnings or add an extra
bit of config to silence them.
/* webpack.config.js */
// ...
externals: {
// use for react 15.4.+
'react/lib/ReactMount': true,
// use for React any version below that
'react-dom/lib/ReactMount': true,
}
// ...Teaspoon also allows extending itself and adding new pseudo selectors using a fairly straight forward API.
To add a new method for all collection types add it to $.fn
(or $.prototype if the jQuery convention bothers you).
// Returns all DOM node descendants and filters by a selector
$.fn.domNodes = function(selector) {
return this
.find(':dom')
.filter(selector)
}
// also works with shallowRender()
$().render().domNodes('.foo')If you want to make a method only available to either instance of element collections you can extend
$.instance.fn or $.element.fn following the same pattern as above.
For new pseudo selectors you can use the createPseudo API which provides
a hook into the css selector engine used by teaspoon: bill. Pseudo selectors do
introduce a new object not extensively covered here, the Node. A Node is a light abstraction that
encapsulates both component instances and React elements, in order to provide a common traversal API across tree types.
You can read about them and their properties here.
…Teaspoon does what it can to abstract away the differences between element and instance collections into a common
暂无开放 Issues,或尚未同步最近议题。