gpt4 book ai didi

javascript - 如何测试构造函数中抛出的错误?

转载 作者:行者123 更新时间:2023-12-02 21:03:05 28 4
gpt4 key购买 nike

我试图用我的 chai 测试捕获构造函数中抛出的错误:

'use strict'

const chai = require('chai')
const expect = chai.expect

describe('A rover must be placed inside the platform', function() {
it('A Rover at position -1 2 S should throw an error', function() {
expect(new Rover(-1, 2, 'N')).should.throw(Error ('Rover has landed outside of the platform'));
})
})


class Rover {
constructor(x, y, heading) {
this.x = x;
this.y = y;
this.heading = heading;

if (this.x > 5 || this.x < 0 || this.y > 5 || this.y < 0) {
throw Error(`Rover has landed outside of the platform`);
}
}
}

构造函数正确地抛出错误,但测试没有捕获它:

A rover must be placed inside the platform
1) A Rover at position -1 2 S should throw an error


1 failing

1) A rover must be placed inside the platform
A Rover at position -1 2 S should throw an error:
Error: Rover has landed outside of the platform

是否有可能用 chai 捕获构造函数中抛出的错误?

最佳答案

您可以将对象创建包装在函数调用中,然后期望抛出异常。

expect(function () {
new Rover(-1, 2, 'N');
}).to.throw('Rover has landed outside of the platform');

参见related回答。

关于javascript - 如何测试构造函数中抛出的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290392/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com