Gathering detailed insights and metrics for jest-serializer-vue-tjw
Gathering detailed insights and metrics for jest-serializer-vue-tjw
Gathering detailed insights and metrics for jest-serializer-vue-tjw
Gathering detailed insights and metrics for jest-serializer-vue-tjw
vue-cli-plugin-jest-serializer-vue-tjw
Vue CLI Plugin wrapper for Jest Serializer Vue (TJW)
jest-serializer-vue
A jest serializer for Vue snapshots
jest-serializer-html
Jest snapshot serializer that beautifies HTML.
enzyme-to-json
convert enzyme wrapper to a format compatible with Jest snapshot
npm install jest-serializer-vue-tjw
Improved arrow function detection in snapshots
Published on 06 Jun 2023
Allow settings to be stored in package.json
Published on 29 Aug 2021
Sorting Attributes is enabled by default
Published on 03 Apr 2021
New API setting to clear Inline Functions from snapshots
Published on 07 Mar 2021
A bandaid for Istanbul
Published on 04 Mar 2021
Remove data-cy from snapshots
Published on 16 Oct 2020
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
33 Stars
111 Commits
7 Forks
2 Watching
6 Branches
1 Contributors
Updated on 16 Feb 2024
JavaScript (82.87%)
Vue (17.13%)
Cumulative downloads
Total Downloads
Last day
-23.3%
1,574
Compared to previous day
Last week
-28.7%
7,712
Compared to previous week
Last month
3%
44,709
Compared to previous month
Last year
-3.9%
466,142
Compared to previous year
Jest Vue snapshot serializer
Logo made by Aurora Wooton (age 14)
Quotes:
"This looks fantastic! This might sell me on testing." - Views on Vue podcast (#99)
Sections:
The following can all be adjusted in your vue.config.js
settings or package.json
.
data-server-rendered="true"
data-test="whatever"
data-testid="whatever"
data-test-id="whatever"
data-v-1234abcd=""
<!-- whatever -->
data-qa="whatever"
id="testWhatever"
class="test-whatever"
href="[object Object]"
This is the before and after of using the default formatting options from v2, and the default formatting options in v3. You can now customize the formatting as well in v3 (See API).
npm install --save-dev jest-serializer-vue-tjw
jest-serializer-vue
in your dependencies or devDependencies it can be removed.1"snapshotSerializers": [ 2 "<rootDir>/node_modules/jest-serializer-vue-tjw" 3]
-- -u
at the end so it will update any existing snapshots, for example:
npm run test:unit -- -u
.toMatchSnapshot('optional snapshot name');
in your tests:Example:
1import { shallowMount } from '@vue/test-utils'; 2import MyComponent from './MyComponent.vue'; 3 4describe('MyComponent.vue', () => { 5 describe('Created', () => { 6 test('Renders correctly with default props', () => { 7 const wrapper = shallowMount(MyComponent); 8 9 expect(wrapper) 10 .toMatchSnapshot(); 11 }); 12 }); 13});
data-test="whatever"
data-testid="whatever"
data-test-id="whatever"
data-v-whatever=""
will be removed. These are attributes added by Vue to help scope styles. Removing them from your snapshots makes updating scoped dependencies easier.<div class=""></div>
becomes <div class></div>
.<svg><path></path></svg>
becomes <svg><path /></svg>
.Example: These are the kind of diffs you can expect to see when migrating from v2 to v3.
1 <div> 2- <h1 data-test="pageTitle" data-test-id="pageTitle" data-testid="pageTitle"> 3+ <h1> 4 The above specific data-attrubutes are removed by default. 5 </h1> 6 <div> 7- <span class="active" data-v-b3d95ac7=""> 8+ <span class="active"> 9 These data-v ID's are removed too by default. 10 </span> 11 <!----> 12 <!-- There's an option you can turn on to remove all HTML comments too --> 13 <!-- It's turned off by default, since they usually represent a v-if="false" --> 14 <!-- and maybe you want to know about that. If not, set removeComments: true --> 15 </div> 16 17 <div> 18- <h3 class="inline-block">Default formatting is improved</h3> <span><i class="fa fa-spinner"></i> <span class="sr-only">Loading...</span></span> <a><button type="button class="primary"><i class="fa fa-plus"></i> 19+ <h3 class="inline-block">Default formatting is improved</h3> 20+ <span> 21+ <i class="fa fa-spinner"></i> 22+ <span class="sr-only">Loading...</span> 23+ </span> 24+ <a> 25+ <button class="primary" type="button> 26+ <i class="fa fa-plus"></i> 27 The formatting here is completely customizable (see API). 28- </button></a> 29+ </button> 30+ </a> 31- <svg style=""> 32+ <svg style> 33- <path d="M 10,150 L 70,10 L 130,150 z"></path> 34+ <path d="M 10,150 L 70,10 L 130,150 z" /> 35 </svg> 36 </div> 37 </div>
Though all default settings are designed to be the best choice for most people, if you want to opt out of these (or opt-in to other changes, like removing HTML comments from snapshots) you can via a settings object in your Vue config. Note, some changes cannot currently be avoided (self-closing enforcement and empty attribute trimming).
vue.config.js
in the root of your project (or create it, if you do not have one).jest-serializer-vue
v2.0.2 settings:1// vue.config.js 2module.exports = { 3 pluginOptions: { 4 jestSerializer: { 5 clearInlineFunctions: false, 6 // All available options: https://github.com/beautify-web/js-beautify/blob/master/js/src/html/options.js 7 formatting: { 8 unformatted: ['code', 'pre', 'em', 'strong', 'span'], 9 indent_inner_html: true, 10 indent_char: ' ', 11 indent_size: 2, 12 sep: '\n' 13 }, 14 removeClassTest: false, 15 removeComments: false, 16 removeDataTest: false, 17 removeDataTestid: false, 18 removeDataTestId: false, 19 removeDataQa: false, 20 removeDataCy: false, 21 removeDataVId: false, 22 removeIdTest: false, 23 removeIstanbulComments: false, 24 removeServerRendered: true, 25 sortAttributes: false, 26 stringifyObjects: false 27 } 28 } 29};
ALL SETTINGS ARE OPTIONAL. The defaults are below. If you like them, you don't need to add anything to your Vue config.
In your vue.config.js
file:
1module.exports = { 2 pluginOptions: { 3 jestSerializer: { 4 attributesToClear: [], 5 clearInlineFunctions: false, 6 // All available formatting options: https://github.com/beautify-web/js-beautify/blob/master/js/src/html/options.js 7 formatting: { 8 indent_char: ' ', 9 indent_inner_html: true, 10 indent_size: 2, 11 inline: [], 12 sep: '\n', 13 unformatted: ['code', 'pre'] 14 }, 15 removeClassTest: false, 16 removeComments: false, 17 removeDataTest: true, 18 removeDataTestid: true, 19 removeDataTestId: true, 20 removeDataQa: false, 21 removeDataCy: false, 22 removeDataVId: true, 23 removeIdTest: false, 24 removeIstanbulComments: true, 25 removeServerRendered: true, 26 sortAttributes: true, 27 verbose: true, 28 // Experimental features: 29 addInputValues: false, 30 stringifyObjects: false 31 } 32 } 33};
Alternatively, you can place your settings in the package.json
. If a jestSerializer
object exists here, we skip looking for a vue.config.js
file (useful for those with complex configs, Nuxt users, or those not using Vue-CLI).
In your package.json
file:
1{ 2 "name": "your_app", 3 "scripts": {}, 4 "devDependencies": {}, 5 6 "jestSerializer": { 7 "attributesToClear": [], 8 "clearInlineFunctions": false, 9 "//": "All available formatting options: https://github.com/beautify-web/js-beautify/blob/master/js/src/html/options.js", 10 "formatting": { 11 "indent_char": " ", 12 "indent_inner_html": true, 13 "indent_size": 2, 14 "inline": [], 15 "sep": "\n", 16 "unformatted": ["code", "pre"] 17 }, 18 "removeClassTest": false, 19 "removeComments": false, 20 "removeDataTest": true, 21 "removeDataTestid": true, 22 "removeDataTestId": true, 23 "removeDataQa": false, 24 "removeDataCy": false, 25 "removeDataVId": true, 26 "removeIdTest": false, 27 "removeIstanbulComments": true, 28 "removeServerRendered": true, 29 "sortAttributes": true, 30 "verbose": true, 31 "// ": "Experimental features:", 32 "addInputValues": false, 33 "stringifyObjects": false 34 } 35}
Setting | Default | Description |
---|---|---|
attributesToClear | [] | Takes an array of attribute strings, like ['title', 'id'] , to remove the values from these attributes. <input title id class="stuff"> . |
clearInlineFunctions | false | Replaces <div title="function () { return true; }"> or this <div title="(x) => !x"> with this placeholder <div title="[function]"> . |
formatting | See above example | These options format the snapshot. See all available options here. |
removeClassTest | false | Removes all CSS classes that start with "test", class="test-whatever" . Warning: Don't use this approach. Use data-test instead. It is better suited for this because it doesn't conflate CSS and test tokens. |
removeComments | false | Removes all HTML comments from your snapshots. This is false by default, as sometimes these comments can infer important information about how your DOM was rendered. However, this is mostly just personal preference. |
removeDataTest | true | Removes data-test="whatever" from your snapshots if true. To also remove these from your production builds, see here. |
removeDataTestid | true | Removes data-testid="whatever" from your snapshots if true. |
removeDataTestId | true | Removes data-test-id="whatever" from your snapshots if true. |
removeDataQa | false | Removes data-qa="whatever" from your snapshots if true. data-qa is usually used by non-dev QA members. If they change in your snapshot, that indicates it may break someone else's E2E tests. So most using data-qa prefer they be left in by default. |
removeDataCy | false | Removes data-cy="whatever" from your snapshots if true. data-cy is used by Cypress end-to-end tests. If they change in your snapshot, that indicates it may break an E2E tests. So most using data-cy prefer they be left in by default. |
removeDataVId | true | Removes data-v-1234abcd="" from your snapshots. Important if a 3rd-party component uses scoped styles, to prevent ID changes from breaking your mount based tests when updating a dependency. |
removeIdTest | false | Removes id="test-whatever" or id="testWhatever" from snapshots. Warning: You should never use ID's for test tokens, as they can also be used by JS and CSS, making them more brittle. Use data-test-id instead. |
removeIstanbulComments | true | Removes /* istanbul ignore next */ cov_1lmjj6lxv1.f[3]++; comments from snapshots when functions are inside HTML attributes. See v3.16.0 release notes for more details. |
removeServerRendered | true | Removes data-server-rendered="true" from your snapshots if true. |
sortAttributes | true | Sorts the attributes inside HTML elements in the snapshot. This helps make snapshot diffs easier to read. |
verbose | true | Logs to the console errors or other messages if true. Strongly recommended if using experimental features. |
addInputValues | false | EXPERIMENTAL Displays the value of form fields. <input> becomes <input value="whatever"> in your snapshots. Requires you pass in wrapper , not wrapper.html() . On deeply nested components, it may exceed callstack. |
stringifyObjects | false | EXPERIMENTAL Replaces title="[object Object]" with title="{a:'asdf'}" in your snapshots, allowing you to see the data in the snapshot. Requires you to pass in wrapper , not wrapper.html() . This is still a work in progress. On deeply nested components, it may exceed callstack. |
What is the best approach for targeting elements in a test? - Use data-test
when targeting multiple elements, or data-test-id
(or data-testid
if you don't like the extra hyphen) when targeting a unique element.
1test('Click link', () => { 2 const wrapper = shallowMount(LinkList); 3 const linkList = wrapper.find('[data-test-id="linkList"]'); 4 const domLink = linkList.findAll('[data-test="link"]').at(0); 5 6 domLink.trigger('click'); 7 8 expect(specialFunction) 9 .toHaveBeenCalledWith('https://passed-in-url.com'); 10}); 11
I have some code that I don't want formatted. How do I "opt out" of the settings for one test? - You can skip the snapshots and just do a string comparison directly, without a snapshot. This is useful when the actual whitespace in the DOM is important and needs to be captured properly without formatting being applied.
1test('Spacing around links is accurate', () => {
2 const wrapper = shallowMount(YourComponent);
3 const section = wrapper.find('[data-test-id="specificSection"]');
4
5 expect(section.html())
6 .toEqual(`<div data-test-id="specificSection">
7 <a href="#">link</a><a href="#">link</a> <a href="#">link</a>
8 <a href="#">link</a> <a href="#">link</a>
9</div>`);
10});
How do I override the settings for just one test? - This is a little complicated, but doable. The following is a basic example. You can refer to the test setup/helpers file in this repo for a more complex example.
1describe('YourComponent.vue', () => { 2 beforeEach(() => { 3 jest.resetModules(); 4 }); 5 6 test('Overriding snapshot settings for one test', () => { 7 jest.doMock('../../../vue.config.js', function () { 8 return { 9 pluginOptions: { 10 jestSerializer: { 11 removeComments: true, 12 stringifyObjects: true 13 } 14 } 15 }; 16 }); 17 18 const wrapper = shallowMount(YourComponent); 19 const section = wrapper.find('[data-test-id="specificSection"]'); 20 21 expect(section) 22 .toMatchSnapshot(); 23 }) 24});
How do I opt out of stringifyObjects or addInputValues for one test? - This is actually much easier. These experimetnal features can only be done on a Vue VNode. So if you do .html()
prior to sending it, it will always skip these transforms. This allows you to use these experimental features more easily, while opting out of the more troublesome tests.
1test('Assuming stringifyObjects is enabled', () => { 2 const wrapper = shallowMount(YourComponent); 3 4 expect(wrapper) 5 .toMatchSnapshot('Stringify objects and add input values'); 6 7 expect(wrapper.html()) 8 .toMatchSnapshot('Opt out of stringify objects and adding input values'); 9});
Vitest actually uses the same snapshot library under the hood as Jest, so this library will work with it as well.
npm install --save-dev jest-serializer-vue-tjw
/vite.config.js
file point to a setup file:
1import { defineConfig } from 'vite'; 2 3export default defineConfig({ 4 test: { 5 setupFiles: [ 6 './tests/unit/setup.js' 7 ] 8 } 9});
/tests/unit/setup.js
file:
1import vueSnapshotSerializer from './serializer.js'; 2 3expect.addSnapshotSerializer(vueSnapshotSerializer);
/tests/unit/serializer.js
file:
1const jestSerializerVueTJW = require('jest-serializer-vue-tjw'); 2 3const helpers = { 4 isHtmlString: function (received) { 5 return ( 6 typeof(received) === 'string' && 7 ( 8 received.startsWith('<') || 9 received.startsWith('"<') 10 ) 11 ); 12 }, 13 isVueWrapper: function (received) { 14 return ( 15 typeof(received) === 'object' && 16 typeof(received.html) === 'function' 17 ); 18 } 19}; 20 21module.exports = { 22 test: function (received) { 23 return helpers.isHtmlString(received) || helpers.isVueWrapper(received); 24 }, 25 print: function (received) { 26 // force to a string 27 received = received?.html && received?.html() || received; 28 return jestSerializerVueTJW.print(received); 29 } 30};
/package.json
, like so:
1{ 2 "jestSerializer": { 3 "sortAttributes": true, 4 "verbose": true 5 } 6}
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
0 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 2
Reason
Found 1/30 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
32 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More