Where to put common data in jest tests

孤街醉人 提交于 2020-12-30 04:51:20

问题


I am not sure how to organize code for jest testing.

I have all my tests under __tests__ and all my mocks under __mocks__. Now I have some data I want to share between tests: they are not a mock of an existing function, they are just some javascript object I'd like to use in different files.

Should I create a __data__ directory?

Or put them under __mocks__ anyway?

Or in the __tests__ directory without putting -test in the file name?


回答1:


The short answer is anywhere you want.

JavaScript has had a lot of different stages in its life and a lot of different types of people using it. Which is probably why most tools these days are highly configurable, to allow for personalization (customization.)

Even Jest itself shows these signs. For instance the test matcher will look for tests in either __tests__ folders or with files that are contain .spec or .test.

Or as per their docs in a visual manner:

├── __tests__
│   └── component.spec.js # test
│   └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test

With regards to fixtures and other test files the answer is the same, there is no one way to do it.

Pick what works for you.

I recommend for the __tests__ structure placing fixture data close to the test thats using it, and if multiple tests need access then move it further up the project until its in a common place.

My preference is a tests folder to keep the tests, fixtures, and testing separate to the src code.




回答2:


I mostly agree with @Alex.

But usually, rather than always moving data to a different file, I prefer to keep real API mock data for one specific case inside the test file itself.

I treat them like the PropType section of React Components, keeping them at the button of the test file (__test__, __spec__, *test.js or *.spec.js) but inside the file unless I have to share.

Here a super simple example with axios:

src/__mocks__/axios.js

export default {
  get: jest.fn(() => Promise.resolve({ data: [] })),
};

Then axios is mocked, because of that now if we want to test a super simple wrapper API utility like:

import Axios from 'axios';

export const yourMethod = async () => {
  return new Promise(resolve => {
    Axios.get(`yourAPIEndPoint`)
      .then(result => {
        resolve([...result.data]);
      })
      .catch(e => {
        console.error('should treat the error', e);
      });
  });
};

For me the one test could only be:

import Axios from 'axios';
import { yourMethod } from './borrame';

describe('yourMethod TestCase', () => {
  it('it returns the data you expect', async () => {
    // Specific response for this test case.
    Axios.get.mockImplementationOnce(() =>
      Promise.resolve({
        data: yourMethodMockData,
      })
    );

    const result = await yourMethod();
    expect(result[0].id).toBe(yourMethodRawMockData[0].id);
  });
});

/**
 * Specific Test Data
 */
const yourMethodMockData = [
  {
    id: '12345',
    name: 'Name for 12345',
  },
];

Even though, if the same mock data is going to be reused outside the test files, I move this mock data to different .js inside a __test__ folder and export it to be reused.

I have even created mockAPIGenerators when I have to "generate" the .json data based on API call params, but for me the general rule to follow is always to KIS

So at the button as a constant in the same test file, unless it's not enough for you 😉.



来源:https://stackoverflow.com/questions/47326877/where-to-put-common-data-in-jest-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!