2017-07-06 53 views
2

我用ts-jestjest用打字稿來寫我的測試文件。如何處理一個模塊和打字稿類型的笑話模擬功能

我很困惑如何輸入模塊的模擬功能。

這裏是我的代碼:

./module.ts

import {IObj} from '../interfaces'; 

const obj: IObj = { 
    getMessage() { 
    return `Her name is ${this.genName()}, age is ${this.getAge()}`; 
    }, 

    genName() { 
    return 'novaline'; 
    }, 

    getAge() { 
    return 26; 
    } 
}; 

export default obj; 

./module.test.ts

import * as m from './module'; 

describe('mock function test suites',() => { 

    it('t-1',() => { 
    // I think the jest.Mock<string> type here is not correct. 
    m.genName: jest.Mock<string> = jest.fn(() => 'emilie'); 
    expect(jest.isMockFunction(m.genName)).toBeTruthy(); 
    expect(m.genName()).toBe('emilie'); 
    expect(m.getMessage()).toEqual('Her name is emilie, age is 26'); 
    expect(m.genName).toHaveBeenCalled(); 

    }); 

}); 

如何輸入模塊m的模擬功能genName

typescript給我在這裏的錯誤:Error:(8, 7) TS2540:Cannot assign to 'genName' because it is a constant or a read-only property.

回答

0

你想嘲笑模塊,然後修改其中的導出函數。這應該取代您的進口聲明。

jest.mock('./module',() => ({ 
    genName: jest.fn().mockImplementation(() => 'emilie') 
}))