#testing #reactjs #mocha.js #enzyme
#тестирование #reactjs #mocha.js #фермент
Вопрос:
Я пытаюсь выполнить фиктивный тест с помощью фермента над компонентом. тест собирается проверить контекст. несмотря на то, что я пишу тот же код, что и документация enzyme, контекст всегда пуст.
import React from 'react';
import { shallow } from 'enzyme';
import Overlay from '../../../../app/components/Overlay/Overlay';
describe('<Overlay />', () => {
it.only('return a context', () => {
const wrapper = shallow(<Overlay />, { context: { foo: 10 } });
console.log(wrapper.context());
// expect(wrapper.context().foo).to.equal(10);
});
})
результат теста:
<Overlay />
{}
✓ return a context
где я ошибаюсь?
Ответ №1:
Поскольку детали Overlay
компонента не указаны, я предполагаю, что контекст в нем не используется (пожалуйста, проверьте childContextTypes
и getChildContext
определены правильно)
Например, обратитесь к объяснению контекстов в документах react
Я использовал тот же пример, чтобы включить тест,
import React from 'react';
export default class Button extends React.Component {
render() {
return (
<button style={{ background: this.context.color }}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: React.PropTypes.string,
};
class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
}
class MessageList extends React.Component {
getChildContext() {
return { color: 'purple' };
}
render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
}
MessageList.childContextTypes = {
color: React.PropTypes.string,
};
Я создал тест для Button
компонента, как показано ниже,
import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import Button from '../../src/components/SampleComp';
describe.only('<Button />', () => {
it('assert for context', () => {
const wrapper = shallow(
<Button />,
{ context: { color: 'red' } }
);
expect(wrapper.context().color).to.equal('red');
expect(wrapper.context('color')).to.equal('red');
});
});
<Button />
✓ assert for context
1 passing (214ms)
Это подтвердит его правильно.