DEV Community

Arman Shojaei
Arman Shojaei

Posted on

Writing test in Nuxt project

Hi guys, I have some HTTP requests in one of my Nuxt plugins and I want to know, is it right to test that HTTP requests?

When I want to write test for my component, do I need to test those HTTP requests? like:

describe('--> TestComponent:', () => {
  // #01
  it('fetched data should have ID, first_name and last_name', async () => {
    console.log('TODO: Should find a what to test plugins')
  });

  // #02
  it('should have loading', async () => {
    await wrapper.setData({
      loading: true
    })
    expect(wrapper.find('.loading').exists()).toBe(true)
  });

  // #03
  it('should have fullName', async () => {
    await wrapper.setData({
      loading: false,
    })
    expect(wrapper.find('.fullName').exists()).toBe(true)
  });
});
Enter fullscreen mode Exit fullscreen mode

Or it's not right to do this?

Top comments (3)

Collapse
 
benjioe profile image
Benjioe • Edited

If your API changes, you probably want's to know what components you have to change,

You can write that's kind of tests for that (it's call Contract Testing), but I prefer to use type.
Do you use TypeScript ? Does your API is written in TypeScript or have a swagger?

Collapse
 
arishojaei profile image
Arman Shojaei • Edited

The API is GraphQL and created with Php/Laravel. I use typescript in my Nuxt project, does it help to write less test? if yes, could you explain how, please?

Collapse
 
benjioe profile image
Benjioe • Edited

I will write a post with a full explain, but in short :

  1. You generate TypeScript typing from GraphQL using tools.
  2. Add/Replace the result files in your client project.
  3. Type your fetch's result with generated files.
// Generated
type dataType = {
  field: string;
};

async function fetchData(): Promise<dataType> {
  const fetchResult = await fetch("dataUrl");
  const json = await fetchResult.json();

  return json as dataType;
}

async function testIt() {
  const res = await fetchData();
  console.log(res.field); // get a typescript error if field no more in dataType
} 
Enter fullscreen mode Exit fullscreen mode

Each time you update your API, make the 2 first step. If there is changes, you're client won't compile (if he use an out of date field).