TypeError:无法设置未定义的属性“ xxx”

时间:2019-12-16 14:12:18

标签: javascript node.js typescript jestjs

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

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);
    }
..
}

1 个答案:

答案 0 :(得分:4)

请尝试以下操作:

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。

相关问题