如何在开玩笑的例外中进行测试

时间:2020-10-05 23:09:30

标签: javascript node.js unit-testing jestjs

我是Jest的初学者,我正在做一个程序以研究更多JS。测试有效,但是可以用异常替换try / catch吗?我相信这仍然不是用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)
    }
  })
})

这是我的课程:

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用.toThrow(error?)

注意:您必须将代码包装在一个函数中,否则错误将不会被捕获并且断言将失败。

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');
  });
});

具有覆盖率报告的单元测试结果:

 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