How can I test asynchronous code?

describe('how to test function with setTimeout', () => {
  let sample = null
  beforeEach(() => {
    sample = jasmine.createSpy('sampleFunction')
    jasmine.clock().install()
  })
  afterEach(() => {
    jasmine.clock().uninstall()
  })
  it('is only invoked after 1000 milliseconds', () => {
    setTimeout(sample, 1000)
    jasmine.clock.tick(999)
    expect(sample).not.toHaveBeenCalled()
    jasmine.clock.tick(1)
    expect(sample).toHaveBeenCalled()
  })
})
describe('how to test function with setInterval', () => {
  let dummy = null
  beforeEach(() => {
    dummy = jasmine.createSpy('dummy')
    jasmine.clock().install()
  })
  afterEach(() => {
    jasmine.clock().uninstall()      
  })    
  it('checks to see number of times function is called', () => {
    setInterval(dummy, 1000)
    jasmine.clock().tick(999)
    expect(dummy.calls.count()).toBe(0)
    jasmine.clock().tick(1000)
    expect(dummy.calls.count()).toBe(1)
    jasmine.clock().tick(1)
    expect(dummy.calls.count()).toBe(2)
  })
})
// You can pass a `done` callback to any of the following:
// `beforeAll`, `afterAll`, `beforeEach`, `afterEach`, `it`
// The `done` MUST be called when the async work is done or 
// the test will timeout with an error.
const getLink = (name) => `https://api.github.com/users/${name}`
const getJson = response => response.json()
const getInfo = (name) => fetch(getLink(name)).then(getJson)

describe('the getInfo function', () => {
  it('gets the correct information', (done) => {
    getUserInfo('debugme').then((data) => {
      expect(data.name).toBe('debugme')
      done()
    })
  })
})

Last updated

Was this helpful?