【发布时间】:2020-07-19 22:02:08
【问题描述】:
我正在尝试测试一个同时包含 React Context 的提供者和消费者的组件。请参阅下面的 App.tsx。 提供者在一个也处理状态的包装类中。
如何模拟 ConfigurationContextProvider 包装类,以便它可以正确地向消费者提供 loadedStatus 值以测试 App.tsx 的各种呈现?
App.tsx:
public render(): React.ReactNode {
return (
<ConfigurationContextProvider>
<ConfigurationContext.Consumer>
{ ({
loadedStatus,
}): ReactElement => {
switch( loadedStatus ){
case ConfigStatus.GoodConfiguration:
return ( this.renderApp());
case ConfigStatus.NotLoaded:
return ( this.renderUnloadedApp() );
case ConfigStatus.BadConfiguration:
return ( this.renderBadConfiguration() );
}
}}
</ConfigurationContext.Consumer>
</ConfigurationContextProvider>
)}
ContextProvider.tsx:
export const ConfigurationContext = React.createContext<ConfigurationState | undefined>(undefined);
export enum ConfigStatus {
NotLoaded,
BadConfiguration,
GoodConfiguration
}
export interface ConfigurationState{
loadedStatus: ConfigStatus;
baseUrl: URL;
}
export class ConfigurationContextProvider extends Component< {}, ConfigurationState> {
constructor( props: {} ){
super(props);
this.state = {
loadedStatus: ConfigStatus.NotLoaded,
baseUrl: null
}
}
async componentDidMount(): Promise<void> {
await this.loadConfiguration();
}
setConfiguration(configuration: Response): void {
const URL_KEY = 'BASE_URL';
const URL_VALUE = configuration[URL_KEY];
if (!Object.prototype.hasOwnProperty.call(configuration, URL_KEY))
{
this.setState({ loadedStatus: ConfigStatus.BadConfiguration });
console.error(`Missing field in configs: ${ URL_KEY }`);
}
else {
try{
this.setState({
loadedStatus: ConfigStatus.GoodConfiguration,
baseUrl: new URL(URL_VALUE),
});
}
catch {
this.setState({ loadedStatus: ConfigStatus.BadConfiguration });
console.error(`Bad URL in environment configs - ${ URL_KEY } : ${ URL_VALUE }`);
}
}
}
loadConfiguration(): Promise<void> {
const configPromise: Promise<Response> = fetch('./env.json');
return configPromise.then( (response) => response.json())
.then( (config: Response) => this.setConfiguration(config));
}
render(): React.ReactNode {
return (
<ConfigurationContext.Provider value = { {
...this.state,
} }>
{this.props.children}
</ConfigurationContext.Provider>
)
}
}
【问题讨论】:
标签: typescript mocking jestjs react-context react-testing-library