我是打字稿新手,我编写了这段代码来测试一下方法,

describe('book', () => {

    let hostelClient: HostelClient;


    it('should book', async () => {

        hostelClient.getRequestByIdAsync = jest.fn().mockReturnValue({});

        // Assert
        let exceptionThrown = false;
        expect(exceptionThrown).toBe(false);
     });

});


但是我有这个错误:

 TypeError: Cannot set property 'getRequestByIdAsync' of undefined




@Service()
export class HostelClient  {

    constructor() {
        throw new Error('not allowed);
    }
..
}

最佳答案

请尝试以下方法:

describe('book', () => {

let hostelClient: HostelClient = new HostelClient();


it('should book', async () => {

    hostelClient.getRequestByIdAsync = jest.fn().mockReturnValue({});

    // Assert
    let exceptionThrown = false;
    expect(exceptionThrown).toBe(false);
 });
});


在您的示例中,您正在定义变量,但没有将变量实例化为新的hostelClient。

09-25 18:53