我正在尝试使用mocha框架的简单测试用例
我写过简单的打字稿
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get height() {
return this.height;
}
set height(value) {
if (typeof value !== 'number') {
throw new Error('"height" must be a number.');
}
this.height = value;
}
get width() {
return this.width;
}
set width(value) {
if (typeof value !== 'number') {
throw new Error('"width" must be a number.');
}
this.width = value;
}
get area() {
return this.width * this.height;
}
get circumference() {
return 2 * this.width + 2 * this.height;
}
}
var rectangle= new Rectangle(10,20);
module.exports = Rectangle;
但是在尝试编写测试用例时如下:
"use strict"
require('babel-register')({
presets: ['es2015']
});
// Import chai.
import * as chai from 'chai';
var path = require('path');
// Import the Rectangle class.
let Rectangle = require(path.join(__dirname, '..', 'rectangle.js'));
const should = chai.should;
var expect = require('chai').expect;
describe('Rectangle', () => {
describe('#width', () => {
let rectangle;
beforeEach(() => {
// Create a new Rectangle object before every test.
rectangle = new Rectangle(10, 20);
});
it('returns the width', () => {
// This will fail if "rectangle.width" does
// not equal 10.
rectangle.width.should.equal(10);
});
});
});
但测试用例失败
我不明白这里的错误
任何帮助将不胜感激
答案 0 :(得分:0)
如果您查看docs for Should,您会看到:
var should = require(' chai')。should()// 实际调用函数
所以你的代码需要看起来像这样:
import * as chai from 'chai';
...
const should = chai.should();
此外,在您的情况下,您无需使用path
,您应该可以这样做:
let Rectangle = require('../rectangle.js');
答案 1 :(得分:0)
您显示的错误是由无限递归引起的。您应该将包含setter和getters 的实际值的变量命名为setter和getter本身。。以下是width
:
class Rectangle {
private _width: number;
constructor(width: number) {
this._width = width;
}
get width(): number {
return this._width;
}
set width(value: number) {
this._width = value;
}
}
const rectangle = new Rectangle(10);
console.log(rectangle.width);
rectangle.width = 100;
console.log(rectangle.width);
// Cannot do this, as it won't compile: rectangle.width = "platypus";
否则,使用你的代码,当构造函数执行this.width = ...
时,调用setter,this.width = ...
再次调用setter,再次,再次调用...
Nitzan是正确的,您必须致电 chai.should()
,而不仅仅是访问它。