JEST 快照测试:如何在 JEST 测试结果中忽略部分快照文件



问题:忽略 .snap 文件测试结果的某些部分

这里的问题是:我的测试中有一些组件具有随机值,我并不真正关心测试它们。 有没有办法忽略我的 X.snap 文件的一部分? 因此,当我将来运行测试时,它不会给我测试失败的结果。

现在,您还可以为这些情况使用属性匹配器。

通过示例,以便能够对这些对象使用快照:

const obj = {
  id: dynamic(),
  foo: 'bar',
  other: 'value',
  val: 1,
};

您可以使用 :

expect(obj).toMatchSnapshot({
  id: expect.any(String),
});

Jest 只会检查 id 是否为字符串,并像往常一样处理快照中的其他字段。

实际上,您需要模拟移动部件。

如开玩笑文档中所述:

您的测试应该是确定性的。也就是说,在未更改的组件上多次运行相同的测试应该每次都产生相同的结果。您有责任确保生成的快照不包含特定于平台的数据或其他非确定性数据。

如果它与时间有关,您可以使用

Date.now = jest.fn(() => 1482363367071);

我知道这是一个很老的问题,但我知道还有一个解决方案。您可以修改要忽略的属性,因此它将始终是恒定的,而不是随机/动态的。这最适合使用第三方代码的情况,因此可能无法控制非确定性属性生成
例:

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();
    });
});

您可以忽略快照测试中的某些部分,以替换 HTML 中的属性。使用带有测试库的笑话,它看起来像这样:

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, '');
}

我用它来覆盖时刻的fromNow,使我的快照具有确定性:

import moment, {Moment} from "moment";
moment.fn.fromNow = jest.fn(function (this: Moment) {
  const withoutSuffix = false;
  return this.from(moment("2023-01-12T20:14:00"), withoutSuffix);
});

最新更新