我遇到了一个问题,如果我export * from submodule
(使用ES6模块语法和babel)我无法mock
子模块使用来自入口点的Jest
函数。我想知道是否有人可以提供帮助...
例如,鉴于此结构:
+ __tests__
| |- index.js
+ greeter
| |- index.js
| |- submodule.js
|- index.js
这段代码:
index.js
import { sayHello } from "./greeter";
export const greet = (name) => sayHello(name);
greeter/index.js
export * from "./submodule.js";
greeter/submodule.js
export const sayHello = (name) => console.log(`Hello, ${name}`);
__tests__/index.js
import { greet } from "../index";
import * as greeter from "../greeter";
describe("greet", () => {
it("Should delegate the call to greeter.sayHello", () => {
const name = "John";
greet(name);
});
});
这一切都很好,当测试运行时,它就会通过。 Hello, John
按预期打印到控制台。让我觉得有价值的好处是index.js
完全没有意识到greeter
模块的结构,所以我可以重构和重构代码而不用担心我的消费者。
greeter.sayHello
... 时,Rub 来了
__tests__/index.js
import { greet } from "../index.js";
import * as greeter from "../greeter";
greeter.sayHello = jest.fn();
describe("greet", () => {
it("Should delegate the call to greeter.sayHello", () => {
const name = "John";
greet(name);
expect(greeter.sayHello).toHaveBeenCalledWith(name);
});
});
现在没有按预期传递测试 - 我收到错误:
Test suite failed to run
TypeError: Cannot set property sayHello of [object Object] which only has a getter
...(stack trace)
将import
中的欢迎__tests__/index.js
更改为:
import * as greeter from "../greeter/submodule";
使测试通过,但将耦合放回我的测试代码中。
还有其他办法吗?
答案 0 :(得分:0)
要在要测试的文件上模拟导入的方法,需要确保在导入文件(index.js)之前运行了模拟程序,如下所示:
let valueFromServer = "ed02"
label.text = unicodeMapper(rawUnicode: valueFromServer)