如何覆盖从打字稿中其他文件导入的功能?

时间:2020-01-30 11:03:12

标签: typescript

我在getPerson文件中声明了一个名为msq.ts的函数,在我的app.ts文件中,我只想将其替换为新的实现。

在我的msq.ts文件中

export function getPerson(): Promise<{ name: string, id: number }> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve({ name: "manas", id: 2 });
        }, 5000);
    })
}

在我的app.ts文件中

import * as msq from "../msq";


msq.getPerson = function():Promise<{name:string,id:number}>{
    return Promise.resolve({name:"manas",id:2});
}

但是当我尝试替换功能时,这显示以下错误

无法分配给getPerson,因为它是只读属性

1 个答案:

答案 0 :(得分:0)

如果我们用对象文字将其包装并默认导出该对象,则可以覆盖该函数。

msq.ts文件中

function getPerson(): Promise<{ name: string, id: number }> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve({ name: "manas", id: 2 });
        }, 5000);
    })
}

export default {
     getPerson
}

app.ts文件中

import  msq from "../msq";

// now we can override the getPerson the way we want

msq.getPerson = function():Promise<{name:string,id:number}>{
    return Promise.resolve({name:"manas",id:2});
}

如果我们正在进行单元测试(使用笑话),那么我们可以轻松地使用jest.fn()对其进行模拟

 import user from "../user";
 import msq from "../msq";

 // now we can override the getPerson the way we want

 msq.getPerson = jest.fn().mockResolvedValue({ name: "manas", id: 2 });

 it("user.getUserInfo must resolve the person with id 2",async()=>{

      const result = await user.getUserInfo();
      expect(result).toEqual({name:"manas",id:2});

 });