下面的摘录(摘自docs):
<div style='height: 0'>
<!-- the quantity of <br> elements must create vertical overflow -->
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<!-- this does not work without the space character -->
</div>
我没有将import React from 'react'
import { render, cleanup } from '@testing-library/react'
import 'jest-dom/extend-expect'
import { NameContext, NameProvider, NameConsumer } from '../react-context'
afterEach(cleanup)
/**
* Test default values by rendering a context consumer without a
* matching provider
*/
test('NameConsumer shows default value', () => {
const { getByText } = render(<NameConsumer />)
expect(getByText(/^My Name Is:/)).toHaveTextContent('My Name Is: Unknown')
})
/**
* To test a component tree that uses a context consumer but not the provider,
* wrap the tree with a matching provider
*/
test('NameConsumer shows value from provider', () => {
const tree = (
<NameContext.Provider value="C3P0">
<NameConsumer />
</NameContext.Provider>
)
const { getByText } = render(tree)
expect(getByText(/^My Name Is:/)).toHaveTextContent('My Name Is: C3P0')
})
/**
* To test a component that provides a context value, render a matching
* consumer as the child
*/
test('NameProvider composes full name from first, last', () => {
const tree = (
<NameProvider first="Boba" last="Fett">
<NameContext.Consumer>
{value => <span>Received: {value}</span>}
</NameContext.Consumer>
</NameProvider>
)
const { getByText } = render(tree)
expect(getByText(/^Received:/).textContent).toBe('Received: Boba Fett')
})
/**
* A tree containing both a providers and consumer can be rendered normally
*/
test('NameProvider/Consumer shows name of character', () => {
const tree = (
<NameProvider first="Leia" last="Organa">
<NameConsumer />
</NameProvider>
)
const { getByText } = render(tree)
expect(getByText(/^My Name Is:/).textContent).toBe('My Name Is: Leia Organa')
})
和first
传递给last
的道具。
假设,这三个定义如下:
NameProvider
我们是否允许在NameContext = createContext()
NameProvider = NameContext.Provider
NameConsumer = NameContext.Consumer
内传递value
道具以外的道具。
如果是,请您分享一个例子。我似乎也无法在react文档中找到它。
提前谢谢! :D
答案 0 :(得分:1)
从这些文档来看还不是很清楚,但是NameContext.Provider
和NameProvider
之间存在细微差别。 NameContext.Provider
是从React.createContext
返回的原始提供者,并且仅以value
作为道具。
在testing-library
文档中,他们没有解释,但是他们创建了一个单独的NameProvider
,该文件包装了NameContext.Provider
,并提供了一个first/last
prop接口,像这样的东西:
const NameProvider = ({ first, last, children }) => (
<NameContext.Provider value={{ first, last }}>
{children}
</NameContext.Provider>
)
这允许您创建具有受限接口的Provider,这在(例如)您正在编写供其他开发人员使用的库并且不想让他们完全访问Provider的库时很有用。 value
道具。