Skip to main content

通过常量间接输入

比如下面代码,我们有一个 tellName 使用到了常量 name

// config.ts

export const config = {
allowTellAge: true,
age: 18,
getAge() {
return 18;
},
};

export const name = "nansen";
export const gold = 3;
// tellName.ts

import { name } from "./config";

export function tellName() {
return name;
}

我们可以直接 mock config.ts 导出的内容。

// tellName.spec.ts

import { tellName } from "./tellName";

vi.mock("./config", () => {
return {
name: "n",
};
});

describe("通过常量间接输入", () => {
it("should tell the name", () => {
const name = tellName();
expect(name).toBe("n");
});
});

注意,用上面的方式 mock 的话,会将 config.ts 的所有导出内容改变。

即本来 goldconfig 也被导出了的,但 mock 之后就没有了,只会有 name

这时,我们可以用参数 importOriginal 和 API vi.importActual 来拿到其他导出内容。

// tellName.spec.ts
import { tellName } from "./tellName";

vi.mock("./config", async (importOriginal) => {
const config = await importOriginal();

return {
...config,
name: "n",
};
});

describe("通过常量间接输入", () => {
it("should tell the name", () => {
const name = tellName();
expect(name).toBe("n");
});
});
// tellName.spec.ts
import { tellName } from "./tellName";

vi.mock("./config", async () => {
const config = await vi.importActual("./config");

return {
...config,
name: "n",
};
});

describe("通过常量间接输入", () => {
it("should tell the name", () => {
const name = tellName();
expect(name).toBe("n");
});
});

更推荐使用参数 importOriginal 来处理,因为不需要将路径再写一次,可以让代码更干净。