Sandro Rey
Sandro Rey

Reputation: 2989

TypeError: Cannot set property 'xxx' of undefined

I am new in typescript, I made this piece of code to test a method with jest,

describe('book', () => {

    let hostelClient: HostelClient;


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

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

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

});

but I have this error:

 TypeError: Cannot set property 'getRequestByIdAsync' of undefined

and

@Service()
export class HostelClient  {

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

Upvotes: 0

Views: 1375

Answers (1)

Inch High
Inch High

Reputation: 845

Please try this:

describe('book', () => {

let hostelClient: HostelClient = new HostelClient();


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

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

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

In your example, you are defining the variable but you aren't instantiating the variable as a new hostelClient.

Upvotes: 4

Related Questions