我正在尝试为NextSeo创建一个Jest Mock,在这里我可以对传递给Meta的道具进行断言。
我在下面有一个基本的工作示例,但是我不确定如何在我的Mock中包含道具以对其进行断言。
元组件
const Meta = (props: Props) => {
return (
<NextSeo
title={props.title == 'Homepage' ? appMeta.title : props.title}
description={
props.title == 'Homepage' ? appMeta.description : props.description
}
/>
);
};
export default Meta;
元单元测试
jest.mock('next-seo', () => ({
NextSeo: '<div></div>', // I am trying to add props here
}));
describe('<ContactUs/>', () => {
it('can render with default props', () => {
const ContactUsWrapper = shallow(
<Meta title="title" description="description" />
);
expect(NextSeo).toEqual('<div></div>');
});
});
我要实现的目标:
模拟:
jest.mock('next-seo', () => ({
NextSeo: '<div>{props.title} {props.desctription}</div>',
}));
规格:
expect(NextSeo).toEqual('<div>title description</div>');
答案 0 :(得分:0)
您可以将NextSeo
组件模拟为功能组件。例如
index.tsx
:
import React from 'react';
import { NextSeo } from './next-seo';
type Props = any;
const Meta = (props: Props) => {
const appMeta = { title: '', description: '' };
return (
<NextSeo
title={props.title === 'Homepage' ? appMeta.title : props.title}
description={props.title === 'Homepage' ? appMeta.description : props.description}
/>
);
};
export default Meta;
next-seo.tsx
:
import React from 'react';
export const NextSeo = ({ title, description }) => <span></span>;
index.test.tsx
:
import Meta from './';
import React from 'react';
import { mount } from 'enzyme';
jest.mock('./next-seo', () => ({
NextSeo: (props) => (
<div>
{props.title} {props.description}
</div>
),
}));
describe('<ContactUs/>', () => {
it('can render with default props', () => {
const ContactUsWrapper = mount(<Meta title="title" description="description" />);
expect(ContactUsWrapper).toMatchSnapshot();
});
});
测试结果:
PASS stackoverflow/60759940/index.test.tsx (7.958s)
<ContactUs/>
✓ can render with default props (37ms)
› 1 snapshot updated.
Snapshot Summary
› 1 snapshot updated from 1 test suite.
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 1 updated, 1 total
Time: 9.08s
index.test.tsx.snap
:
// Jest Snapshot v1
exports[`<ContactUs/> can render with default props 1`] = `
<Meta
description="description"
title="title"
>
<NextSeo
description="description"
title="title"
>
<div>
title
description
</div>
</NextSeo>
</Meta>
`;