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

52

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

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

5个回答

44

现在您也可以针对这些情况使用属性匹配器

例如,可以使用快照与以下对象:

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

您可以使用:

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

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


3
是的,使用以下语法:toMatchSnapshot({id: expect.any(String)}, "快照名称") - Julien TASSIN

35

实际上,你需要模拟移动的部分。

如在 Jest 文档中所述:

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

如果涉及到时间,可以使用

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

起初听起来很奇怪,但后来我意识到,这应该适用于 Math.random,所以我的使用情况应该已经被覆盖了。 - Lazerbeak12345
如果您的ID是进行更改的提交的哈希值(即head ref),那该怎么办? - SkyzohKey

4

我知道这是一个比较老的问题,但是我知道另一种解决方案。您可以修改要忽略的属性,使其始终保持不变而不是随机/动态。这对于在使用第三方代码时可能无法控制非确定性属性生成的情况最为适用。


示例:

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

1
谢谢。这真的很有用。根据您的方法,我编写了一个简单的函数,在快照和快照子节点上递归调用该函数,并且将替换任何不确定性属性。 此外,您可以编辑您的回答,提到这种方法最适合在使用第三方代码时,因此可能无法控制不确定性属性生成的情况。 - sktguha

3

您可以忽略快照测试中 HTML 属性替换的某些部分。在使用 jest 和 testing-library 时,它会类似于这样:

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

0
我使用这个来覆盖 moment 的 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);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接