Насмешливые родовые функции с шуткой - PullRequest
1 голос
/ 14 мая 2019

Я безуспешно пытался издеваться над общей функцией с помощью jest.Вот способ, который мне кажется правильным:

interface ServiceInterface {
    get<T>(): T;
}

class Service implements ServiceInterface {
    get = jest.fn(<T>(): T => null);
}

При компиляции выдает следующую ошибку:

error TS2416: Property 'get' in type 'Service' is not assignable to the same property in base type 'ServiceInterface'.
  Type 'Mock<{}, any[]>' is not assignable to type '<T>() => T'.
    Type '{}' is not assignable to type 'T'.

Не могли бы вы показать мне правильный способ сделать это?

Спасибо

Ответы [ 2 ]

0 голосов
/ 15 мая 2019

Я думаю, если вы создадите интерфейс, давайте сделаем его как универсальный интерфейс вместо настройки универсального для каждого свойства.

interface ServiceInterface<T> {
  get(): T;
}

Когда вы создаете макет с помощью Jest:

class Service<T> implements ServiceInterface<T> {
  get = jest.fn<T, []>((): T => null);
}

const instance = new Service<string>();
const result = instance.get(); // typeof result === "string"

Для вашего случая, что вам нужно смоделировать это возвращаемое значение get()

interface ServiceInterface {
  get<T>(): T;
}

const mockedGet = jest.fn();

class Service implements ServiceInterface {
  get<T>(): T {
    return mockedGet();
  }
}

const instance = new Service();
mockedGet.mockReturnValue("Hello!");
const result = instance.get<string>(); // now, result is a string
0 голосов
/ 14 мая 2019

Я использую sinon для моей насмешки, которую можно установить с помощью:

npm i sinon --save-dev

, а затем, чтобы смоделировать в одном из ваших тестов, вы можете сделать что-то вроде этого:

const mock = sinon.mock(service); // you want the value passed in to mock to be the actualy object being mocked
mock.expects('get').returns(null) // this would expect get to be called once and the return value is null
mock.restore(); // restores all mocked methods
mock.verify(); // verifies the expectations
...