Laura
Laura

Reputation: 99

test fails toThrow

I am having a problem with testing my application (for studies) for when there is an equal category name in the database. Although the category is not added to the table again, the test does not pass.

When I add a new category that is not in the bank, it says Matcher Error: the received value must be a function but what to expect cannot test a variable?

And I don't know where I might be going wrong

class DAO

export default class CategoryDAO {
  constructor(conn) {
    this._conn = conn
  }
  async add(category) {
    if (!(category instanceof Category)) {
      throw new Error("The object is not of type category")
    }
    try {
      const categories = await this._conn.query(`SELECT * FROM category`)
      
      if (categories.some(c => c.name === category.name)) {
        throw new Error("The category has already been registered")
      }
      await this._conn.query(`INSERT INTO category (name) VALUES (?)`, [category.name])
    } catch (error) {
      throw new Error(error)
    }
  }
}

Test

describe("Tests for Class Category", () => {
  let conn = new Connection()

  beforeAll(async () => {
    await conn.conect()
  });

  afterAll(async () => {
    await conn.close();
  })

  it("Creating author successfully", async () => {
    const categoryDAO = new CategoryDAO(conn)
    const category = new Category("Devops")
    await categoryDAO.add(category)
    expect(category.name).toBeDefined()
  })

  it("Add must throw error when another author is registered", async () => {
    const categoryDAO = new CategoryDAO(conn)
    const category = new Category("Devops")
    await categoryDAO.add(category)
    expect( category).toThrow(new Error(`The category has already been registered`))
  })

Log

Tests for Class Category › Add must throw error when another author is registered

    Error: The category has already been registered

      17 |       await this._conn.query(`INSERT INTO category (name) VALUES (?)`, [category.name])
      18 |     } catch (error) {
    > 19 |       throw new Error(error)
         |             ^
      20 |     }
      21 |   }
      22 | }

Upvotes: 0

Views: 57

Answers (1)

tadman
tadman

Reputation: 211580

This is a wild guess, but this is based on the pattern in the documentation you linked to:

await expect(categoryDAO.add(category)).rejects.toThrow({
  ... // Your error.
});

Upvotes: 1

Related Questions