【发布时间】:2018-05-10 16:56:12
【问题描述】:
在 mocha/chai 设置中,我尝试将 babel-plugin-rewire 与 sinon 结合使用,以在同一模块中测试和存根函数。这些是下面的示例文件:
首先,一个 index.js 和一个同时使用 sinon 和 babel-plugin-rewire 的测试文件。重新布线工作,但由于某种原因,我的存根不起作用。它所应用的函数永远不会被存根,只会返回原始值:
// index.js
function foo() {
return "foo";
}
export function bar() {
return foo();
}
export function jar() {
return "jar";
}
//index.test.js
import chai from "chai";
import sinon from "sinon";
import * as index from "./index";
const expect = chai.expect;
const sandbox = sinon.sandbox.create();
describe("babel-plugin-rewire", () => {
it("should be able to rewire", () => {
index.default.__set__("foo", () => {
return "rewired"; // successfullly rewires
});
expect(index.bar()).to.equal("rewired"); // works fine
index.default.__ResetDependency__("foo");
expect(index.bar()).to.equal("bar"); // works fine
});
});
describe("sinon", () => {
afterEach(() => {
sandbox.restore();
});
it("should call the original jar", () => {
expect(index.jar()).to.equal("jar"); // works fine
});
it("should call the stubbed jar", () => {
sandbox.stub(index, "jar").returns("stub");
expect(index.jar()).to.equal("stub"); // fails
});
});
这里是两个单独使用 sinon 存根的示例文件。同样的事情也会发生:
// stub.js
export function stub() {
return "stub me";
}
// stub.test.js
import * as stub from "./stub";
import sinon from "sinon";
import chai from "chai";
const expect = chai.expect;
const sandbox = sinon.createSandbox();
const text = "I have been stubbed";
describe("sinon stubs", () => {
afterEach(() => {
sandbox.restore();
});
it("should stub", () => {
sandbox.stub(stub, "stub").returns(text);
expect(stub.stub()).to.equal(text); // fails
});
});
这是用于 mocha 的 babelrc
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"rewire"
]
}
如果我从插件中删除重新布线,问题就会消失。虽然很明显这意味着我不能使用 rewire,正如我之前提到的,我需要它来在同一个依赖项中存根函数。这是模块的错误还是我在这里遗漏了什么?
【问题讨论】:
标签: javascript unit-testing mocha.js sinon stub