【发布时间】:2017-08-13 15:18:33
【问题描述】:
问题:忽略 .snap 文件测试结果的某些部分
这里的问题:我的测试中有一些组件具有随机值,我并不真正关心测试它们。有什么方法可以忽略我的 X.snap 文件的一部分吗?所以当我以后运行测试时,它不会给我测试失败的结果。
【问题讨论】:
标签: react-native jestjs snapshot
问题:忽略 .snap 文件测试结果的某些部分
这里的问题:我的测试中有一些组件具有随机值,我并不真正关心测试它们。有什么方法可以忽略我的 X.snap 文件的一部分吗?所以当我以后运行测试时,它不会给我测试失败的结果。
【问题讨论】:
标签: react-native jestjs snapshot
您可以忽略快照测试中的某些部分,替换 HTML 中的属性。将 jest 与测试库一起使用,它看起来像这样:
it('should match snapshot', async () => {
expect(removeUnstableHtmlProperties(await screen.findByTestId('main-container'))).toMatchSnapshot();
});
function removeUnstableHtmlProperties(htmlElement: HTMLElement) {
const domHTML = prettyDOM(htmlElement, Infinity);
if (!domHTML) return undefined;
return domHTML.replace(/id(.*)"(.*)"/g, '');
}
【讨论】:
我知道这是一个很老的问题,但我知道另一种解决方案。您可以修改要忽略的属性,因此它将始终保持不变而不是随机/动态。这最适合您使用第三方代码的情况,因此可能无法控制非确定性属性的生成
示例:
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Card from './Card';
import toJSON from 'enzyme-to-json';
Enzyme.configure({ adapter: new Adapter() });
describe('<Card />', () => {
it('renders <Card /> component', () => {
const card = shallow(
<Card
baseChance={1}
name={`test name`}
description={`long description`}
imageURL={'https://d2ph5fj80uercy.cloudfront.net/03/cat1425.jpg'}
id={0}
canBeIgnored={false}
isPassive={false}
/>
);
const snapshot = toJSON(card);
// for some reason snapshot.node.props.style.backgroundColor = "#cfc5f6"
// does not work, seems the prop is being set later
Object.defineProperty(snapshot.node.props.style, 'backgroundColor', { value: "#cfc5f6", writable: false });
// second expect statement is enaugh but this is the prop we care about:
expect(snapshot.node.props.style.backgroundColor).toBe("#cfc5f6");
expect(snapshot).toMatchSnapshot();
});
});
【讨论】:
现在您也可以在这些情况下使用property matcher。
通过示例能够对这些对象使用快照:
const obj = {
id: dynamic(),
foo: 'bar',
other: 'value',
val: 1,
};
你可以使用:
expect(obj).toMatchSnapshot({
id: expect.any(String),
});
Jest 只会检查 id 是否是一个字符串,并会像往常一样处理快照中的其他字段。
【讨论】:
toMatchSnapshot({id: expect.any(String)}, "snapshot name")
实际上,您需要模拟移动部件。
如jest docs中所述:
您的测试应该是确定性的。也就是说,在未更改的组件上多次运行相同的测试应该每次都产生相同的结果。您有责任确保生成的快照不包含特定于平台的数据或其他非确定性数据。
如果是与时间有关的东西,你可以使用
Date.now = jest.fn(() => 1482363367071);
【讨论】:
Math.random,所以应该涵盖我的用例。