/ / Enzyme renderuje stylizowany komponent z motywem - reagjs, jestjs, enzym, stylizowany komponent

Enzyme renderuje stylizowany komponent z motywem - reactjs, jestjs, enzym, stylizowane komponenty

ja używam react z styled-components, i jest enzyme do moich testów. Mam problem z testowaniem komponentu tematycznego, który wciąż powoduje błędy z powodu theme od styled-components.

Mój komponent to:

const Wrapper = styled.header`
position: fixed;
top: 0;
left: 0;

display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;

width: 100%;
height: 64px;

background-color: ${({ theme }) => theme.colors.main.default};
color: ${({ theme }) => theme.colors.main.text};
`

Mój test to:

it("should render a <header> tag", () => {
const renderedComponent = shallow(<Wrapper />)
expect(renderedComponent.type()).toEqual("header")
})

Jest to błąd:

<Wrapper /> › should render a <header> tag

TypeError: Cannot read property "main" of undefined

at Object.<anonymous>._styledComponents2.default.header.theme (app/containers/AppBar/Wrapper.js:13:182)

Zasadniczo generuje błąd, ponieważ themejest niezdefiniowany, więc nie może odczytać colors właściwość w nim. Jak mogę przekazać motyw do mojego komponentu?

Odpowiedzi:

0 dla odpowiedzi № 1

Biorąc to pod uwagę ...

${({ theme }) => theme.colors.main.default};

... i ten błąd ...

TypeError: Cannot read property "main" of undefined

... wygląda mi na to props.theme robi istnieją wewnątrz komponentu w stylu, ale motyw nie ma colors własność. Chciałbym spojrzeć albo na definicję motywu, albo na konfigurację ThemeProvider za źródło problemu.


0 dla odpowiedzi nr 2

Rozwiązuję ten problem, tworząc funkcję pomocnika obejścia. Mam obiekt motywów zawierający ciemny i jasny motyw:

    const CHANNEL = "__styled-components__";
const broadcast = createBroadcast(themes.dark);

const nodeWithThemeProp = node => {
return React.cloneElement(node, { [CHANNEL]: broadcast.subscribe });
};

export function mountWithTheme(node, { context, childContextTypes } = {}) {
return mount(
nodeWithThemeProp(node),
{
context: Object.assign({}, context, {[CHANNEL]: broadcast.subscribe}),
childContextTypes: Object.assign({}, {[CHANNEL]: createBroadcast(themes.dark).publish}, childContextTypes)
}
);
}

teraz mogę uzyskać stan i motyw komponentu opakowania: mountWithTheme(<Component {...props} />)