Моя цель - проверить мою функцию: fetchStats
Ожидаемые результаты: Это console.logs
Сообщение об ошибке и сбое. и устанавливает _isFetching
в false.
Фактические результаты: Ошибка обнаружена, но console.logs не запущен и isFetching не установлен.
Код ниже:
fetchStats:
fetchStats() {
this._isFetching = true;
// fetch stats after building url and replacing invalid characters
return new Promise(async (resolve, reject) => {
await API.fetchStats(this.rsn)
.then(jres => {
this.skills = jres.main.skills;
this._isFetching = false;
resolve('success');
})
.catch(err => {
console.log(err);
console.log('error retreiving stats');
this._isFetching = false;
reject('Failed to retreive stats');
})
.finally(() => {
this._isFetching = false;
});
});
}
Тест:
it("catches thrown errors", () => {
this.apiFetchStats.throws(new Error());
const player = Player.fromJSON(
JSON.stringify({
rsn: 'rsn',
skills: {
overall: { level: 2000 },
attack: { attack: {} },
defence: { defence: {} },
},
})
);
sinon.spy(console, "log");
player.fetchStats();
expect(this.apiFetchStats).to.be.calledOnce;
expect(this.apiFetchStats).to.have.thrown();
expect(console.log).to.have.been.calledTwice;
expect(player.isFetching()).to.be.false;
console.log.restore();
});
});
Первые два ожидают прохождение штрафа, сигнализируя, что оно имеетбыл вызван и выдал, поэтому он должен быть в блоке catch, но console.log не был вызван и isFetching не был установлен. Кто-нибудь имеет представление о том, что идет не так?
Решено путем добавления ожиданий к .then
из player.fetchStats
, например, так:
player.fetchStats().then(() => {
expect(this.apiFetchStats).to.be.calledOnce;
expect(this.apiFetchStats).to.have.thrown();
expect(console.log).to.have.been.calledTwice;
expect(player.isFetching()).to.be.false;
})
.finally(() => { console.log.restore(); });