【问题标题】:Expect class to throw an Error if the argument is not a string?如果参数不是字符串,期望类抛出错误?
【发布时间】:2019-01-12 06:02:18
【问题描述】:

我正在学习 Jest。我正在尝试测试,当我创建一个类并且传递的参数不是抛出错误的字符串时。

// class.js
export default class FooClass {
    constructor(value) {
        if (typeof value !== 'string') throw new Error('Value should be a String.')
        this.value = value
    }
}

// class.test.js
import FooClass from './class'

it('should throw an Error if the value is not a String', () => {
    expect(new FooClass(123)).toThrowError('Value should be a String.')
})

Jest 可以通过这个测试,只是返回 Test failed。

【问题讨论】:

  • 欢迎来到 StackOverflow。您能否通过编辑问题使这一点更清楚一些。社区需要了解 a) 您期望看到的内容,b) 您在实践中看到的内容,以及 c) 您收到的任何错误消息。谢谢。
  • 你还没有真正描述你的代码有什么问题。

标签: javascript unit-testing ecmascript-6 jestjs


【解决方案1】:

问题是,我调用的是类而不是函数。

// class.js
export default class FooClass {
    constructor(value) {
        if (typeof value !== 'string') throw new Error('Value should be a String.')
        this.value = value
    }
}

// class.test.js
import FooClass from './class'

it('should throw an Error if the value is not a String', () => {
    expect(() => new FooClass(123)).toThrowError('Value should be a String.')
})

现在它正在工作。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多