简体   繁体   中英

How to fix TS error 'type is missing' when working with jest and History?

I'm writing tests and I'm using a mock history object, however TS keeps throwing the below error:

Type '{}' is missing the following properties from type 'Location<IHistoryMock>': pathname, search, state, hash

I'm not sure how to get around this. I've tried extending the History interface and rewriting it every way that I could think of. Here's what I have so far:

import { History, Location } from 'history';

interface IHistoryMock extends History {
  location: Location | any;
}

const historyMock: History<IHistoryMock> = { push: jest.fn(), createHref: () => '', location: { }, listen: jest.fn() };

mount(
  <Router history={historyMock}>
    <Component id="id" />
  </Router>
);

Typescript underlines location: { } and throws the above error. Am I incorrectly extending History ? I need a location to be an empty object here, and I don't want to use the any type.

You can use createLocation function in history library for creating Location mock

import { createLocation } from 'history';
...
const historyMock: History<IHistoryMock> = { push: jest.fn(), createHref: () => '', location: createLocation('/'), listen: jest.fn() };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM