我正在尝试模拟在构造函数中设置为默认值的类属性
class Files {
constructor(queueNumber = 0) {
this.queueNumber = queueNumber;
this.dir = 'JiraResults';
}
...
}
此类基于dir
属性创建目录和文件,对于测试,我需要另一个目录,因此我无需移动真实目录即可运行测试。
[我尝试了许多方法来替换该属性,但所有方法均因与Sinon不同的错误而失败。
const tempDir = 'JiraResults-TEMP';
let stubDir;
describe('Files', () => {
before(() => {
stubDir = sinon.stub(Files.prototype.constructor, 'dir').value(tempDir);
}
...
}
这样我得到了错误TypeError: Cannot stub non-existent own property dir
const tempDir = 'JiraResults-TEMP';
let stubDir;
describe('Files', () => {
before(() => {
stubDir = sinon.stub(Files.prototype, 'dir').value(tempDir);
}
...
}
这样我得到了错误TypeError: Cannot stub non-existent own property dir
const tempDir = 'JiraResults-TEMP';
let stubDir;
describe('Files', () => {
before(() => {
stubDir = sinon.stub(Files.prototype, 'this').value({
dir: sinon.stub().returnsThis(tempDir),
});
}
...
}
这样我得到了错误TypeError: Cannot stub non-existent own property this
我也尝试了其他方法,但从未达到替换属性的地步。
我研究了Sinon文档,但所有示例似乎都不适用于构造函数类。
有人可以给我一个有关如何替换此属性的有效示例吗?
谢谢。
您可以直接更改dir
属性的值,以便被测方法将使用存根dir
。
例如
files.js
:
class Files {
constructor(queueNumber = 0) {
this.queueNumber = queueNumber;
this.dir = "JiraResults";
}
mkdir() {
console.log("make dir: ", this.dir);
}
}
module.exports = Files;
files.test.js
:
const Files = require("./files");
const sinon = require("sinon");
describe("Files", () => {
it("should use stubbed dir", () => {
sinon.spy(console, "log");
const instance = new Files();
instance.dir = "stubbed dir";
instance.mkdir();
sinon.assert.calledWith(console.log, "make dir: ", "stubbed dir");
});
});
单元测试结果:
Files
make dir: stubbed dir
✓ should use stubbed dir
1 passing (7ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
files.js | 100 | 100 | 100 | 100 | |
files.test.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|