2

I have a react native application that needs to use jest-cucumber to write test steps using gherkin style syntax. I was able to write sample step definitions and run them successfully. Now, I need to write a test that makes an API GET call. How can I read the "body" for each of the objects from the response that I get.

Here's what I have so far:

in my step definition file (library.steps.test.js), I am trying to call an api method that is defined in library.js below and trying to grab the description content from the api, but data seems to return "undefined" for me. I don't understand why.

library.feature

Feature: Book tracking

  Scenario: Check out a book.
    Given A user wishes to check out a book from a library with these books:
      | Name                      | Author      |
      | Romeo and Juliet          | Shakespeare |
      | The Origin of the Species | Darwin      |
    When They check out a book with a specific name:
      | Name                      |
      | The Origin of the Species |
    Then It should be marked as checked out.

library.steps.test.js

import { defineFeature, loadFeature } from 'jest-cucumber';
import { Library } from '../library';

const feature = loadFeature('specs/features/library.feature');

defineFeature(feature, (test) => {

  let library;
  let checkedOutBookName;

  // before each test, create a new library
  beforeEach(() => library = new Library())

  test('Check out a book.', ({ given, when, then }) => {
    
    given('A user wishes to check out a book from a library with these books:', (table) => {
      table.forEach(row => library.addBook({ name: row.Name, author: row.Author }))
    })
    
    when('They check out a book with a specific name:', (table) => {
      checkedOutBookName = table[0].Name;
      library.checkoutBook(checkedOutBookName)
    })
    
    then("It should be marked as checked out.", () => {
      expect(library.isCheckedOut(checkedOutBookName)).toBe(true)
    })

    it('Api testing', async function() {
      let data = await library.api()
      console.log("DATA ", data)
      // expect(data?.body)
    })
  
  })
})

library.js

import fetch from "node-fetch";

export class Library {
  constructor() {
    this.books = [];
  }

  api() {
    fetch('https://jsonplaceholder.typicode.com/comments')
      .then(response => {
        return response.json()
      })
  }

  addBook({ name, author }) {
    if (name && author) {
      this.books.push({ name, author, checkedOut: false });
    }
  }

  findBook(name) {
    return this.books.find(book => book.name === name);
  }

  checkoutBook(name) {
    const aBook = this.findBook(name);
    if (aBook) {
      aBook.checkedOut = true;
    }
  }

  isCheckedOut(name) {
    let result = false;
    const aBook = this.findBook(name);
    if (aBook) {
      result = aBook.checkedOut;
    }
    return result;
  }

}
iDan
  • 25
  • 3

0 Answers0