Vitest使用绝对路径创建快照文件

Vitest creates snapshot file using absolute path

提问人:basant 提问时间:11/16/2023 最后编辑:basant 更新时间:11/16/2023 访问量:13

问:

我正在使用如下所示的代码创建一个最生动的快照文件:

import { mount } from '@vue/test-utils'
import AccountLockedView from '../AccountLockedView.vue'

describe('AccountLockedView', () => {
  let wrapper
  beforeEach(() => {
    wrapper = mount(AccountLockedView)
  })

  it('renders AccountLockedView', () => {
    expect(wrapper).toMatchSnapshot()
  })
})

这将生成一个快照文件,该文件的键值为 现在这会导致一个问题,每次有人运行测试用例时,该值都会根据他们的存储库/文件夹位置而变化。 有没有办法以某种方式设置根位置,例如文件夹,以便在创建快照文件后,它不会每次都更改?__file/users/some_user_name/file/path/of/vue/component__filesrc

单元测试 jestjs vite vitest

评论


答:

0赞 birdiewd 12/20/2023 #1

这是我第一次在这里分享解决方案,所以和我一起裸露。

包完成后会吐出一个字符串,所以我手动调用了它,并在离开时翻译了它。jest-styled-components

// vitest.setup.ts

...

// import "jest-styled-components";
import { styleSheetSerializer } from "jest-styled-components/serializer";

...

beforeEach(() => {
  expect.addSnapshotSerializer({
    serialize(val, config, indentation, depth, refs, printer) {
      return (
        styleSheetSerializer
          .serialize(val, config, indentation, depth, refs, printer)
          // scrub local urls out
          .replace(/\/@fs\/.*\/apps\//g, "./apps/")
      );
    },
    test(val) {
      return styleSheetSerializer.test(val);
    },
  });

  ...

});