Monday 24 June 2019

Issue trying to test a http request in a setInterval

Hello, I use Typescript and a class to manage a feature that I'd like to test. This is my simplified code:class Feature { private _names: string[] = []; constructor() { this.fetchNames(); } private fetchNames() { setInterval(() => { MyAPI.getNames() .then(names => this._names = names) .catch(err => console.log(err)); }, 1000) } get names(): string[] { return this._names; } } I use a class to manage my feature but I guess I would have the same problem using a module and functions, because only the names() function would be exported, fetchNames() and _names would be private.​I'd like to test after the first request the names() method returns the correct names. What I tried:describe(`Feature`, () => { let clock: sinon.SinonFakeTimers; beforeEach(() => { clock = sinon.useFakeTimers(); }) afterEach(() => { clock.restore(); }) it(`Should update the names`, async () => { sinon.stub(MyApi, 'getNames').resolves(['Alfred', 'Eve']); const feature = new Feature(); clock.tick(1500); expect(feature.names[0]).equal('Alfred'); }) }) The request is called once and returns the correct names, but I got this error: "AssertionError: expected undefined to equal 'Alfred'".​It'd like to let the _names property and fetchNames() method in private. Thanks for reading, any help appreciated.

Submitted June 25, 2019 at 01:31AM by GreenMonkeyBoy

No comments:

Post a Comment