简体   繁体   中英

Using Jest to write tests for function

I have a function called addToShoppingList and its job is to add the product a user inputs to a shopping list (currently, just an array). I am working on tests using Jest to check if my function is working, but am currently stuck:

index.js

const fetchData = async (product, numOfProducts) => {
  const res = await fetch( ... );
  const data = await res.json();
  return data;
};

// user input for products looks like 'butter 2' 
// selecting Breaskstone's butter (from mockData below)
const addToShoppingList = async (product, numOfProducts = 10, getProducts = fetchData) => {
  const shoppingList = [];

  const item = product.slice(0 ,-2); // i.g. 'butter'
  const i = +product.split(' ').pop() - 1; // i.g. '2' which becomes 1, the index number in array 
  const data = await getProducts(item, numOfProducts);

  // i, which is the index, is used to grab specific item from list of products
  let products = data.items[i].productInfo.name; 
  let manufacturers = data.items[i].productInfo.manufacturer;

  const chosenItem = `${products} from ${manufacturer}`

  shoppingList.push(chosenItem);

  return shoppingList;
};

This isn't great code, but I'm trying to learn how to write tests for the functions above - I am currently using Jest and have this written down so far, but have been getting error messages (which I've been googling and trying to fix). Would love to get tips from unit testing experts on what I'm doing incorrectly:

index.test.js

const mockData = {
  items: [
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Land O Lakes'
      },
    },
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Breakstone'
      },
    },
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Kerrygold',
      },
    }
  ]
};

describe('addToShoppingList', () => {
  const mockProducts = jest.fn();
  mockGetBooks.mockReturnValue(mockData);

   it('should call fetch with correct arguments', async () => {
     await addToShoppingList('product 1', 'numOfResults', mockProducts);
     expect(mockProducts).toBeCalledWith('product 1', 'numOfResults');
   });
});

I would like to test if my addToShoppingList function is working using the mockData I have created above.

Here is an unit test solution:

index.js :

const fetchData = async (product, numOfProducts) => {
  const res = await fetch('https://github.com/mrdulin');
  const data = await res.json();
  return data;
};

// user input for products looks like 'butter 2'
// selecting Breaskstone's butter (from mockData below)
export const addToShoppingList = async (product, numOfProducts = 10, getProducts = fetchData) => {
  const shoppingList = [];

  const item = product.slice(0, -2); // i.g. 'butter'
  const i = +product.split(' ').pop() - 1; // i.g. '2' which becomes 1, the index number in array
  const data = await getProducts(item, numOfProducts);

  // i, which is the index, is used to grab specific item from list of products
  let products = data.items[i].productInfo.name;
  let manufacturers = data.items[i].productInfo.manufacturer;

  const chosenItem = `${products} from ${manufacturers}`;

  shoppingList.push(chosenItem);

  return shoppingList;
};

index.spec.js :

import { addToShoppingList } from '.';

const mockData = {
  items: [
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Land O Lakes'
      }
    },
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Breakstone'
      }
    },
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Kerrygold'
      }
    }
  ]
};

describe('addToShoppingList', () => {
  it('should call fetch with correct arguments', async () => {
    const mockProducts = jest.fn().mockReturnValue(mockData);
    const actualValue = await addToShoppingList('product 1', 100, mockProducts);
    expect(actualValue).toEqual(['Butter from Land O Lakes']);
    expect(mockProducts).toBeCalledWith('product', 100);
  });
});

Unit test result:

 PASS  src/stackoverflow/58807874/index.spec.ts (8.62s)
  addToShoppingList
    ✓ should call fetch with correct arguments (10ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |       70 |       40 |    33.33 |    78.57 |                   |
 index.ts |       70 |       40 |    33.33 |    78.57 |             2,3,4 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.145s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58807874

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM