<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Mocking - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Mocking - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 22:25:35 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/mocking/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Mocking GraphQL with graphql-tools+ ]]>
                </title>
                <description>
                    <![CDATA[ By Jeff M Lowery How to mock up your GraphQL API with realistic values In my last article, I took the original Apollo LaunchPad Posts and Authors API and broke it down into domains and components. I wanted to illustrate how one could organize a large... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mocking-graphql-with-graphql-tools-42c2dd9d0364/</link>
                <guid isPermaLink="false">66d45f7b38f2dc3808b790cf</guid>
                
                    <category>
                        <![CDATA[ Apollo GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Mocking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Testing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 03 Sep 2017 23:15:48 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9cb38c740569d1a4cac9a0.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jeff M Lowery</p>
<h4 id="heading-how-to-mock-up-your-graphql-api-with-realistic-values">How to mock up your GraphQL API with realistic values</h4>
<p>In <a target="_blank" href="https://medium.com/@jefflowery/declarative-graphql-with-graphql-tools-cd1645f94fc">my last article,</a> I took the original Apollo LaunchPad <a target="_blank" href="https://launchpad.graphql.com/1jzxrj179">Posts and Authors API</a> and broke it down into domains and components. I wanted to illustrate how one could organize a large GraphQL project using <a target="_blank" href="https://github.com/apollographql/graphql-tools">graphql-tools</a>.</p>
<p>Now I’d like the API to return mock data when I query it. How?</p>
<h3 id="heading-the-original-source">The original source</h3>
<p>In the original Apollo Launchpad example, we used static data structures and simple mapping resolvers to provide output for queries.</p>
<p>For instance, given this query:</p>
<pre><code class="lang-graphql"><span class="hljs-comment"># Welcome to GraphiQL</span>

<span class="hljs-keyword">query</span> PostsForAuthor {
  author(<span class="hljs-symbol">id:</span> <span class="hljs-number">1</span>) {
    firstName
    posts {
      title
      votes
    }
  }
}
</code></pre>
<p>The output would be:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"author"</span>: {
      <span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"Tom"</span>,
      <span class="hljs-attr">"posts"</span>: [
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Introduction to GraphQL"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">2</span>
        }
      ]
    }
  }
}
</code></pre>
<p>The resolvers object has functions that take care of mapping authors to posts and visa-versa. It’s not truly a mock, though.</p>
<p>The problem is that the more relationships and the more complex the entities become, the more code needs to go into the resolvers. Then more data needs to be provided.</p>
<p>When it comes to testing, tests are likely to sometimes reveal problems in the data or in the resolvers. You really want focus testing of the API itself.</p>
<h3 id="heading-using-mocks">Using mocks</h3>
<p>There are three Node.js modules that make mocking an API quick and easy. The first is part of the <code>graphql-tools</code> module. Using this module, a beginning step is to require or import the method <code>addMockFunctionsToSchema</code> from the module into the root <code>schema.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {
    makeExecutableSchema,
    addMockFunctionsToSchema
} <span class="hljs-keyword">from</span> <span class="hljs-string">'graphql-tools'</span>;
</code></pre>
<p>Then, after creating an executable <code>schema</code> by calling <code>createExecutableSchema</code>, you add your mocks like so:</p>
<pre><code class="lang-js">    addMockFunctionsToSchema({
        <span class="hljs-attr">schema</span>: executableSchema,
    })
</code></pre>
<p>Here’s a full listing of the root <code>schema.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// This example demonstrates a simple server with some relational data: Posts and Authors. You can get the posts for a particular author,</span>
<span class="hljs-comment">// and vice-versa Read the complete docs for graphql-tools here: http://dev.apollodata.com/tools/graphql-tools/generate-schema.html</span>

<span class="hljs-keyword">import</span> {
    makeExecutableSchema,
    addMockFunctionsToSchema
} <span class="hljs-keyword">from</span> <span class="hljs-string">'graphql-tools'</span>;

<span class="hljs-keyword">import</span> {
    schema <span class="hljs-keyword">as</span> authorpostsSchema,
    resolvers <span class="hljs-keyword">as</span> authorpostsResolvers
} <span class="hljs-keyword">from</span> <span class="hljs-string">'./authorposts'</span>;

<span class="hljs-keyword">import</span> {
    schema <span class="hljs-keyword">as</span> myLittleTypoSchema,
    resolvers <span class="hljs-keyword">as</span> myLittleTypeResolvers
} <span class="hljs-keyword">from</span> <span class="hljs-string">'./myLittleDomain'</span>;

<span class="hljs-keyword">import</span> {
    merge
} <span class="hljs-keyword">from</span> <span class="hljs-string">'lodash'</span>;

<span class="hljs-keyword">const</span> baseSchema = [
    <span class="hljs-string">`
    type Query {
        domain: String
    }
    type Mutation {
        domain: String
    }
    schema {
        query: Query,
        mutation: Mutation
    }`</span>
]

<span class="hljs-comment">// Put schema together into one array of schema strings and one map of resolvers, like makeExecutableSchema expects</span>
<span class="hljs-keyword">const</span> schema = [...baseSchema, ...authorpostsSchema, ...myLittleTypoSchema]

<span class="hljs-keyword">const</span> options = {
    <span class="hljs-attr">typeDefs</span>: schema,
    <span class="hljs-attr">resolvers</span>: merge(authorpostsResolvers, myLittleTypeResolvers)
}

<span class="hljs-keyword">const</span> executableSchema = makeExecutableSchema(options);

addMockFunctionsToSchema({
    <span class="hljs-attr">schema</span>: executableSchema
})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> executableSchema;
</code></pre>
<p>So what’s the output? Executing the same query as before yields:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"author"</span>: {
      <span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"Hello World"</span>,
      <span class="hljs-attr">"posts"</span>: [
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Hello World"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">-70</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Hello World"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">-77</span>
        }
      ]
    }
  }
}
</code></pre>
<p>Well, that’s kind of dumb. Every string is “Hello World”, votes are negative, and there will always be exactly two posts per author. We’ll fix that, but first…</p>
<h4 id="heading-why-use-mocks">Why use mocks?</h4>
<p>Mocks are often used in unit tests to separate the functionality being tested from the dependencies that those functions rely on. You want to test the function (the unit), not a whole complex of functions.</p>
<p>At this early stage of development, mocks serve another purpose: to test the tests. In a basic test, you want to ensure first that the test is calling the API correctly, and that the results returned have the expected structure, properties, and types. I think the cool kids call this “shape”.</p>
<p>This offers more limited testing than a queryable data structure, because reference semantics are not enforced. <code>id</code> is meaningless. Nonetheless, mocks offer something to structure your tests around</p>
<h3 id="heading-realistic-mocking">Realistic mocking</h3>
<p>There’s a module called <a target="_blank" href="https://github.com/boo1ean/casual">casual</a> that I really like. It provides reasonable and variable values for a lot of common data types. If you are demonstrating your new API in front of jaded colleagues, it actually looks like you’ve done something special.</p>
<p>Here’s a wish list for mock values to display:</p>
<ol>
<li>Author’s first name should be <strong>first-name-like</strong></li>
<li>Post titles should be variable <strong>lorem ipsum</strong> text of limited length</li>
<li>votes should be positive or zero</li>
<li>the number of posts should vary between 1 and 7</li>
</ol>
<p>First thing is to create a folder called <code>mocks</code>. Next, we’ll add an <code>index.js</code> file to that folder with the mock methods. Finally, the custom mocks will be added to the generated executable schema.</p>
<p>The <strong>casual</strong> library can generate values by data type (<code>String, ID, Int, …</code>) or by property name. Also, graphql-tools MockList object will be used to vary the number of items in a list — in this case <code>posts</code>. So let’s start.</p>
<p><code>Import</code> both casual and MockList into <code>/mocks/index.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> casual <span class="hljs-keyword">from</span> <span class="hljs-string">'casual'</span>;
<span class="hljs-keyword">import</span> {
    MockList
} <span class="hljs-keyword">from</span> <span class="hljs-string">'graphql-tools'</span>;
</code></pre>
<p>Now let create a default export with the following properties:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
    <span class="hljs-attr">Int</span>: <span class="hljs-function">() =&gt;</span> casual.integer(<span class="hljs-number">0</span>),

    <span class="hljs-attr">Author</span>: <span class="hljs-function">() =&gt;</span> ({
        <span class="hljs-attr">firstName</span>: casual.first_name,
        <span class="hljs-attr">posts</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">new</span> MockList([<span class="hljs-number">1</span>, <span class="hljs-number">7</span>])
    }),

    <span class="hljs-attr">Post</span>: <span class="hljs-function">() =&gt;</span> ({
        <span class="hljs-attr">title</span>: casual.title
    })
}
</code></pre>
<p>The <code>Int</code> declaration takes care of all integer types appearing in our schema and it will ensure that <code>Post.votes</code> will be positive or zero.</p>
<p>Next, <code>Author.firstName</code> will be a reasonable first name. MockList is used to ensure the number of posts associated with each Author will be between 1 and 7. Finally, casual will generate a <strong>lorem ipsum</strong> <code>title</code> for each <code>Post</code>.</p>
<p>Now the generated output varies each time the query is executed. And it looks credible:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"author"</span>: {
      <span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"Eldon"</span>,
      <span class="hljs-attr">"posts"</span>: [
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Voluptatum quae laudantium"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">581</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Vero quos"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">85</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Doloribus labore corrupti"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">771</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Qui nulla qui"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">285</span>
        }
      ]
    }
  }
}
</code></pre>
<h3 id="heading-generating-custom-values">Generating custom values</h3>
<p>I just scratched the surface of what casual can do, but it is well-documented and there’s nothing much to add.</p>
<p>Sometimes, though, there are values that have to conform to a standard format. I would like to introduce one more module: <a target="_blank" href="https://www.npmjs.com/package/randexp">randexp</a>.</p>
<p>randexp allows you to generate values conforming to the regexp expression you provide it. For instance, ISBN numbers have the format:</p>
<p><strong>/ISBN-\d-\d{3}-\d{5}-\d/</strong></p>
<p>Now I can add Books to the schema, add books to Author, and generate ISBN and title for each <code>Book</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// book.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-string">`
  type Book {
    ISBN: String
    title: String
}</span>
</code></pre>
<p>mocks.js:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> casual <span class="hljs-keyword">from</span> <span class="hljs-string">'casual'</span>;
<span class="hljs-keyword">import</span> RandExp <span class="hljs-keyword">from</span> <span class="hljs-string">'randexp'</span>;
<span class="hljs-keyword">import</span> {
    MockList
} <span class="hljs-keyword">from</span> <span class="hljs-string">'graphql-tools'</span>;
<span class="hljs-keyword">import</span> {
    startCase
} <span class="hljs-keyword">from</span> <span class="hljs-string">'lodash'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
    <span class="hljs-attr">Int</span>: <span class="hljs-function">() =&gt;</span> casual.integer(<span class="hljs-number">0</span>),

<span class="hljs-attr">Author</span>: <span class="hljs-function">() =&gt;</span> ({
        <span class="hljs-attr">firstName</span>: casual.first_name,
        <span class="hljs-attr">posts</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">new</span> MockList([<span class="hljs-number">1</span>, <span class="hljs-number">7</span>]),
        <span class="hljs-attr">books</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">new</span> MockList([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>])
    }),

<span class="hljs-attr">Post</span>: <span class="hljs-function">() =&gt;</span> ({
        <span class="hljs-attr">title</span>: casual.title
    }),

<span class="hljs-attr">Book</span>: <span class="hljs-function">() =&gt;</span> ({
        <span class="hljs-attr">ISBN</span>: <span class="hljs-keyword">new</span> RandExp(<span class="hljs-regexp">/ISBN-\d-\d{3}-\d{5}-\d/</span>)
            .gen(),
        <span class="hljs-attr">title</span>: startCase(casual.title)
    })
}
</code></pre>
<p>And here’s a new query:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> PostsForAuthor {
  author(<span class="hljs-symbol">id:</span> <span class="hljs-number">1</span>) {
    firstName
    posts {
      title
      votes
    }
    books {
      title
      ISBN
    }
  }
}
</code></pre>
<p>Sample response:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"author"</span>: {
      <span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"Rosemarie"</span>,
      <span class="hljs-attr">"posts"</span>: [
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Et ipsum quo"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">248</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Deleniti nihil"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">789</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Aut aut reprehenderit"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">220</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Nesciunt debitis mollitia"</span>,
          <span class="hljs-attr">"votes"</span>: <span class="hljs-number">181</span>
        }
      ],
      <span class="hljs-attr">"books"</span>: [
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Consequatur Veniam Voluptas"</span>,
          <span class="hljs-attr">"ISBN"</span>: <span class="hljs-string">"ISBN-0-843-74186-9"</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Totam Et Iusto"</span>,
          <span class="hljs-attr">"ISBN"</span>: <span class="hljs-string">"ISBN-6-532-70557-3"</span>
        },
        {
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Voluptatem Est Sunt"</span>,
          <span class="hljs-attr">"ISBN"</span>: <span class="hljs-string">"ISBN-2-323-13918-2"</span>
        }
      ]
    }
  }
}
</code></pre>
<p>So that’s the basics of mocking using graphql-tools plus a couple of other useful modules .</p>
<p><strong>Note</strong>: I use snippets throughout this post. If you want to follow along in a broader context, sample code is <a target="_blank" href="https://github.com/JeffML/graphql_authors_mock">here</a>.</p>
<p>The <a target="_blank" href="https://github.com/JeffML/graphql_authors_mock">Full source</a> is on GitHub for your perusal.</p>
<p>Give me a hand if you found this article informative.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
