Testing methods that rely on Directus SDK with Vitest

55 Views Asked by At

So I am starting out with testing and I cannot get my head around it. I have built a very simple question and answer app where I use Directus to provide the questions and answers. Now I want to write the testing - I suppose it's unit testing - for my functions, but I don't understand how to go about it. I have a Vite application with Typescript and I am using vitest.

Here is my main.ts

function directusSDK(directusURL: string){

if(!directusURL) throw Error("url was faulty!");

const client = createDirectus(directusURL).with(authentication()).with(rest());

async function getQuestions(token: string){
  try {
   if(!token) throw Error("token was faulty!");
  const result = await client.request<Questions[]>(
   withToken(token,
    readItems('Questions', {
     fields: ['*']
    })
   )
  );
  return result;
  } catch (error: any) {
  console.error(error);
 }
}
   }

For the test I wrote a main.test.ts file:

import { directusSDK } from "../src/main";
import { describe, expect, test } from "vitest";

// setup test
test("#Something simple", () => {
  expect(1 + 1).toBe(2);
});

describe("#directusSDK", () => {
  describe("given no url was provided", () => {
    test("an error is thrown", () => {
      expect(() => directusSDK("")).toThrowError();
    });
  });

  describe("given no token was provided", () => {
    test("an error is thrown", () => {
        // URL??
      expect(() => directusSDK("").getQuestions("")).toThrowError();
    });
  });
});

So the first test is just to see if the setup was ok. The second one should assert that an error is thrown once no url was provided. And I think the 3rd one is already dumb. If I insert an empty string into the main method, that will already throw the error, so how can I get past that?

I would need to mock the Directus server completely, right? Wouldn't that mean I could enter any string like just "hello"? And how do I go about fetching the results?

The Vitest docs say I need msw js for that. But I don't really understand what I was seeing there. Maybe someone can lend me a hand on how to go about testing this. Would be greatly appreciated! Thanks guys

0

There are 0 best solutions below