DEV Community

Lam
Lam

Posted on

Jasmine Cheat Sheet

References

[Tests] Event spies

spyOnEvent($('#some_element'), 'click')
$('#some_element').click()
expect('click').toHaveBeenPreventedOn($('#some_element'))
expect('click').toHaveBeenTriggeredOn($('#some_element'))
Enter fullscreen mode Exit fullscreen mode

[Tests] HTML runner

var jasmineEnv = jasmine.getEnv()
jasmineEnv.updateInterval = 250

var htmlReporter = new jasmine.HtmlReporter()
jasmineEnv.addReporter(htmlReporter)

$(function() { jasmineEnv.execute() })
Enter fullscreen mode Exit fullscreen mode

Jasmine jQuery

[Tests] Async

test('works with promises', () => {
  return new Promise((resolve, reject) => {
    ···
  })
})
Enter fullscreen mode Exit fullscreen mode

Make your test return a promise.

[Tests] Creating spies

stub = jasmine.createSpy('stub')
stub('hello')
Enter fullscreen mode Exit fullscreen mode
expect(stub.identity).toEqual('stub')
expect(stub).toHaveBeenCalled()
Enter fullscreen mode Exit fullscreen mode

[Tests] Spies

spyOn(foo, 'setBar')
spyOn(foo, 'setBar').andReturn(123)
spyOn(foo, 'getBar').andCallFake(function() { return 1001; })
foo.setBar(123)
Enter fullscreen mode Exit fullscreen mode
expect(foo.setBar).toHaveBeenCalled()
expect(foo.setBar).toHaveBeenCalledWith(123)
expect(foo.setBar.calls.length).toEqual(2)
expect(foo.setBar.calls[0].args[0]).toEqual(123)
Enter fullscreen mode Exit fullscreen mode

[Tests] Pending

xit('this is a pending test', () => {
  ···
})
Enter fullscreen mode Exit fullscreen mode
xdescribe('this is a pending block', () => {
  ···
})
Enter fullscreen mode Exit fullscreen mode

[Tests] Hooks

beforeEach(() => {
  ···
})
Enter fullscreen mode Exit fullscreen mode
afterEach(() => {
  ···
})
Enter fullscreen mode Exit fullscreen mode

[Tests] Expectations

expect(true).toBe(true)
expect(true).not.toBe(true)
Enter fullscreen mode Exit fullscreen mode
expect(a).toEqual(bar)
Enter fullscreen mode Exit fullscreen mode
expect(message).toMatch(/bar/)
expect(message).toMatch('bar')
Enter fullscreen mode Exit fullscreen mode
expect(a.foo).toBeDefined()
expect(a.foo).toBeUndefined()
expect(a.foo).toBeNull()
Enter fullscreen mode Exit fullscreen mode
expect(a.foo).toBeTruthy()
expect(a.foo).toBeFalsy()
Enter fullscreen mode Exit fullscreen mode
expect(message).toContain('hello')
Enter fullscreen mode Exit fullscreen mode
expect(pi).toBeGreaterThan(3)
expect(pi).toBeLessThan(4)
expect(pi).toBeCloseTo(3.1415, 0.1)
Enter fullscreen mode Exit fullscreen mode
expect(func).toThrow()
Enter fullscreen mode Exit fullscreen mode

[Tests] Writing tests

describe('A suite', () => {
  it('works', () => {
    expect(true).toBe(true)
  })
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)