我是打字稿新手,我编写了这段代码来测试一个方法,
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);
}
..
}
答案 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。