{"id":172,"date":"2022-07-24T22:53:00","date_gmt":"2022-07-24T22:53:00","guid":{"rendered":"https:\/\/www.mitango.app\/?p=172"},"modified":"2025-01-07T22:35:37","modified_gmt":"2025-01-07T22:35:37","slug":"why-you-should-be-using-fixtures-for-your-jest-tests","status":"publish","type":"post","link":"https:\/\/www.mitango.app\/fr\/2022\/07\/24\/why-you-should-be-using-fixtures-for-your-jest-tests\/","title":{"rendered":"Why you should be using Fixtures for your Jest tests"},"content":{"rendered":"<p><a href=\"https:\/\/medium.com\/@crochetfeve0251?source=post_page---byline--5603da165ef5--------------------------------\" target=\"_blank\" rel=\"noopener\"><\/a><\/p>\n\n\n\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\"><h2>Table of Contents<\/h2><nav><ul><li><a href=\"#901a\">Fixtures<\/a><ul><li><a href=\"#40e1\">Advantages<\/a><\/li><li><a href=\"#ac76\">Drawbacks<\/a><\/li><\/ul><\/li><li><a href=\"#390e\">Implementation<\/a><ul><li><a href=\"#741f\">Creating a state<\/a><\/li><li><a href=\"#e7e3\">Mapping the context to the test<\/a><\/li><li><a href=\"#6f56\">Add tests and fixtures<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\n\n\n<p id=\"1162\">Testing your code is always a good practice. However this can easily become time consuming to write tests and maintaining it.<\/p>\n\n\n\n<p id=\"fd98\">In this article we will interest ourselves to a tool that will help us to reduce the code we are writing when we are creating tests.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"901a\">Fixtures<\/h2>\n\n\n\n<p id=\"3642\">The feature in question is named fixture.<\/p>\n\n\n\n<p id=\"ec8b\">This consist of templates files&nbsp;containing&nbsp;configurations for the test that will be loaded each test giving it a different context.<\/p>\n\n\n\n<p id=\"71df\">This allowing a same test to be reused multiples times without having to rewrite the code but instead just by swapping the context we map to this test.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"40e1\">Advantages<\/h3>\n\n\n\n<p id=\"3f11\">The advantage of this approach is obliviously the reduction of code and of duplication of it inside the testing folders.<\/p>\n\n\n\n<p id=\"47ac\">Instead of having to write 3 tests for 3 different cases, we can instead create one test with 3 different contexts changing only the values we inject into the tested code and the expectation concerning its result.<\/p>\n\n\n\n<p id=\"805d\">This method also allow us to have a better organization of our code as we can now have only one test case per file without having numerous files inside one same folder.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ac76\">Drawbacks<\/h3>\n\n\n\n<p id=\"2121\">However the main drawback of this method is that we add complexity inside the test logic that can lead to reduce the speed we are writing one test but as the code is done to be mainly read and maintained this is not a big issue.<\/p>\n\n\n\n<p id=\"44d1\">Another drawback is that we will have to refactor your old fixtures from a tests when we will have to add new logic in a existing function as the tests are not totally isolated.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"390e\">Implementation<\/h2>\n\n\n\n<p id=\"f550\">Now that we learnt what are fixtures we will now see a way to implement the feature inside a Jest testing project if you want to check directly the code it is available directly on this repository:<\/p>\n\n\n\n<p><a href=\"https:\/\/github.com\/CrochetFeve0251\/fixture-example\" target=\"_blank\" rel=\"noopener\">https:\/\/github.com\/CrochetFeve0251\/fixture-example<\/a><\/p>\n\n\n\n<p id=\"7f6a\">The first step will be to create a folder&nbsp;<em>tests<\/em>&nbsp;inside your project to add your test files.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"741f\">Creating a state<\/h3>\n\n\n\n<p id=\"8af4\">The first thing we will have to create is a state to contain the context of each test for that we gonna create a file with the name&nbsp;<em>state.js<\/em>&nbsp;and we will add the following content inside it:<\/p>\n\n\n\n<pre class=\"wp-block-code is-style-light\"><code>const state = {<br>    state: {}<br>};const getTestState = () =&gt; state.state;const setTestState = new_state =&gt; {<br>    state.state = new_state;<br>};module.exports = {<br>    getTestState,<br>    setTestState,<br>}<\/code><\/pre>\n\n\n\n<p id=\"b7a5\">This code create a state that we will reuse later to save the context of the test but also 2 accessors to get and set the value of this state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"e7e3\">Mapping the context to the test<\/h3>\n\n\n\n<p id=\"323d\">Then the next step will be to create a function that will contain the logic mapping the test to its context.<\/p>\n\n\n\n<p id=\"6384\">For that we will create a file&nbsp;<em>tests.js<\/em>&nbsp;inside the&nbsp;<em>tests<\/em>&nbsp;folder and add this content to it:<\/p>\n\n\n\n<pre class=\"wp-block-code is-style-light\"><code>const {setTestState} = require(\".\/state\");module.exports = (fixture,  callback = () =&gt; {}) =&gt; {<br>    const fixtures = require(fixture);fixtures.map(item =&gt; {beforeEach(() =&gt; {<br>            const pattern =  item.name.replace(\/&#91;.*+?^${}()|&#91;\\]\\\\]\/g, '\\\\$&amp;');<br>            const regex = new RegExp(`.*${pattern}$`);<br>            if(regex.test(expect.getState().currentTestName))  {<br>                setTestState({ config: item.config, expected: item.expected });<br>            }<br>        })it(item.name, callback);afterAll(() =&gt; {<br>            setTestState({});<br>        })<br>    });<br>}<\/code><\/pre>\n\n\n\n<p id=\"ad0e\">Inside this file we do multiple things:<\/p>\n\n\n\n<p id=\"e44d\">First we fetch the data from the fixture file by requiring it.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const fixtures = require(fixture);<\/pre>\n\n\n\n<p id=\"1c7b\">Then we iterate on each context inside of the fixture file and we add 3 things:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A&nbsp;<em>beforeEach<\/em>&nbsp;callback that will check if the current test is the right one and if it the case add data to the state.<\/li>\n\n\n\n<li>The test by itself.<\/li>\n\n\n\n<li>A&nbsp;<em>afterAll<\/em>&nbsp;callback that will clean the state.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code is-style-light\"><code>beforeEach(() =&gt; {<br>            const pattern =  item.name.replace(\/&#91;.*+?^${}()|&#91;\\]\\\\]\/g, '\\\\$&amp;');<br>            const regex = new RegExp(`.*${pattern}$`);<br>            if(regex.test(expect.getState().currentTestName))  {<br>                setTestState({ config: item.config, expected: item.expected });<br>            }<br>        })it(item.name, callback);afterAll(() =&gt; {<br>            setTestState({});<br>        })<\/code><\/pre>\n\n\n\n<p id=\"1280\">Once we did that the main logic is now set and we will just have to add tests and fixtures.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6f56\">Add tests and fixtures<\/h3>\n\n\n\n<p id=\"c6d8\">The first thing we will have to do now is to add some dummy code to test.<\/p>\n\n\n\n<p id=\"6036\">For this example that gonna be the function sum that will have the following logic and will be in the file&nbsp;<em>src\/sum.js<\/em>:<\/p>\n\n\n\n<pre class=\"wp-block-code is-style-light\"><code>function sum(a, b) {<br>    return a + b;<br>}<br>module.exports = sum;<\/code><\/pre>\n\n\n\n<p id=\"b8e9\">Then to keep your tests clean we will create two folders in your&nbsp;<em>tests<\/em>&nbsp;folder to separate fixtures from unit tests:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><em>Fixtures<\/em>: For your fixtures.<\/li>\n\n\n\n<li><em>Unit<\/em>: For your unit tests.<\/li>\n<\/ul>\n\n\n\n<p id=\"1c95\">Inside this two folders we will add a&nbsp;<em>sum.js<\/em>&nbsp;file.<\/p>\n\n\n\n<p id=\"ec4a\">For the one in the&nbsp;<em>Fixtures<\/em>&nbsp;folder we will add the following content:<\/p>\n\n\n\n<pre class=\"wp-block-code is-style-light\"><code>module.exports = &#91;<br>    {<br>        name: \"When 1 + 1 should return 2\",<br>        configs: {<br>            value1: 1,<br>            value2: 2,<br>        },<br>        expected: 2<br>    },<br>    {<br>        name: \"When 0 + 0 should return 0\",<br>        configs: {<br>            value1: 0,<br>            value2: 0,<br>        },<br>        expected: 0<br>    }<br>];<\/code><\/pre>\n\n\n\n<p id=\"324c\">For the one in the&nbsp;<em>Unit<\/em>&nbsp;folder we will add the following content:<\/p>\n\n\n\n<pre class=\"wp-block-code is-style-light\"><code>const tests = require('..\/tests');<br>const {getTestState} = require(\"..\/state\");tests('..\/..\/Fixtures\/sum', () =&gt; {<br>    const { configs, expected } = getTestState();<br>    expect(sum(configs.value1, configs.value2)).toBe(expected);<br>});<\/code><\/pre>\n\n\n\n<p id=\"7fd8\">Once we did that, voila our tests with fixtures are ready to be used. I hope you enjoyed this tutorial and that you will be using fixtures for your future projects.<\/p>","protected":false},"excerpt":{"rendered":"<p>Testing your code is always a good practice. However this can easily become time consuming to write tests and maintaining it.<\/p>\n<p>In this article we will interest ourselves to a tool that will help us to reduce the code we are writing when we are creating tests.<\/p>","protected":false},"author":1,"featured_media":173,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[26],"tags":[37,38,36,28,22],"class_list":["post-172","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-testing","tag-fixtures","tag-jest","tag-nodejs","tag-react","tag-testing"],"jetpack_publicize_connections":[],"acf":[],"_links":{"self":[{"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/posts\/172","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/comments?post=172"}],"version-history":[{"count":2,"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/posts\/172\/revisions"}],"predecessor-version":[{"id":416,"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/posts\/172\/revisions\/416"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/media\/173"}],"wp:attachment":[{"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/media?parent=172"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/categories?post=172"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mitango.app\/fr\/wp-json\/wp\/v2\/tags?post=172"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}