我使用react context API在应用程序中设置全局主题。我正在尝试测试使用<ThemeContext.Consumer>
的组件。
这是我在组件中使用它的方式:
<ThemeContext.Consumer>
{({toggleTheme}) => (
<SettingsOption
iconName="color-lens"
optionName={goTheme}
actionType="arrow"
handleAction={() => this.handleAppTheme(toggleTheme)}
showNewLabel={true}
/>
)}
</ThemeContext.Consumer>
单元测试是这样的:
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import Settings from 'containers/Settings'; // to get redux connected component import Setting without {}
import {shallow, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureStore from 'redux-mock-store';
import {Provider} from 'react-redux';
import {ThemeContext} from '../../App';
import {lightTheme} from 'reduxStore/reducers/themeReducer';
configure({adapter: new Adapter()});
const mockStore = configureStore([]);
describe('testing render', () => {
const store = mockStore({
appTheme: {lightTheme},
appUse: {useNumber: 0},
});
const fakeNavigation = {
navigate: jest.fn(),
setParams: jest.fn(),
addListener: jest.fn(),
};
it('Does Settings renders correctly?', () => {
const tree = renderer
.create(
<ThemeContext.Provider value={{theme: 'light', toggleTheme: jest.fn()}}>
<Provider store={store}>
<Settings
navigation={fakeNavigation}
t={(key) => key}
/>
</Provider>
,
</ThemeContext.Provider>,
)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
我得到的错误是这样的:
请注意,如果我评论组件和测试中所有对上下文的使用,则测试通过了
谢谢