简体   繁体   中英

how to test with in jest exceptions

I am a beginner with Jest, I am doing a program to study more JS. The tests work, but could this try / catch be replaced by exceptions? I believe that it is still not the best way to do this test with Jest.

import Category from "../app/models/Category.js"

describe("Test for category", () => {
  it("error for null category", () => {
    try {
      new Category(null)
      console.log("Error: category was created even as null name")
    } catch (err) {
      expect(err.message)
    }
  })
  it("Error for empty category", () => {
    try {
      new Category(" ")
      console.log("Error: category was created with an empty field")
    } catch (err) {
      expect(err.message)
    }
  })
  it("Category registration", () => {
    try {
      new Category("Devops")
      console.log("Category was created successfully!")
    } catch (err) {
      expect(err.message)
    }
  })
})

This is my class:

import { isEmpty, isNull } from "../validate.js"

export default class Category {
  constructor(name) {
    this.name = name
  }

  set name(name) {
    if (isEmpty(name) || isNull(name)) throw new Error(`The category field needs to be filled`)
    this._name = name
  }
  get name() {
    return this._name
  }
}

validate.js

export const isEmpty = value => !notEmpty(value)

export const isNull = value => value === null

Thanks for any help!

Use .toThrow(error?)

Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.

Category.js :

import { isEmpty, isNull } from './validate';

export default class Category {
  constructor(name) {
    this.name = name;
  }

  set name(name) {
    if (isEmpty(name) || isNull(name)) throw new Error(`The category field needs to be filled`);
    this._name = name;
  }
  get name() {
    return this._name;
  }
}

Category.test.js :

import Category from './Category';

describe('Test for category', () => {
  it('error for null category', () => {
    expect(() => new Category(null)).toThrowError('The category field needs to be filled');
  });
  it('Error for empty category', () => {
    expect(() => new Category(' ')).toThrowError('The category field needs to be filled');
  });
  it('Category registration', () => {
    const c = new Category('Devops');
    expect(c._name).toBe('Devops');
  });
});

unit test result with coverage report:

 PASS  src/stackoverflow/64217332/Category.test.js
  Test for category
    ✓ error for null category (11ms)
    ✓ Error for empty category (2ms)
    ✓ Category registration (1ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |    92.31 |      100 |    83.33 |    88.89 |                   |
 Category.js |    85.71 |      100 |    66.67 |    83.33 |                13 |
 validate.js |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        5.502s, estimated 17s

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