Is it possible to get the filename of the rendered font of an element?
Example:
@font-face {
font-family: 'MyFont';
src: url('../../public/fonts/MyFont-Bold.woff2') format('woff2');
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: 'MyFont';
src: url('../../public/fonts/MyFont-Italic.woff2') format('woff2');
font-weight: normal;
font-style: italic;
}
.my-font-bold {
font-family: 'MyFont';
font-weight: bold;
font-style: normal;
}
<p className="my-font-bold"></p>
In this example I would like to get ../../public/fonts/MyFont-Bold.woff2 of the element (because it has font-weight bold and font-family = "MyFont" thanks to the className "my-font-bold").
PS: I would like to do this to make font Vitest tests.
CodeSandbox: https://codesandbox.io/p/sandbox/magical-flower-q87vz7?file=%2Fapp%2Ffont.test.tsx%3A27%2C2
In Javascript it is definitely possible. You just need to leverage the
getComputedStyleto achieve that.Steps to achieve the requirement:
ptag is using.urland return the result else returnnull.Code implementation:
Writing the test for the above function: