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

3j86kqsm  于 9个月前  发布在  Jest
关注(0)|答案(1)|浏览(141)

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

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现在这会导致一个问题,每次有人运行测试用例时,__file值都会根据他们的repo/文件夹位置而改变。有没有办法以某种方式设置根位置,比如src文件夹,这样一旦快照文件被创建,它就不会每次都改变?

bihw5rsg

bihw5rsg1#

这是我第一次在这里分享一个解决方案,对我来说太简单了。
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);
    },
  });

  ...

});

字符串

相关问题