bun
bun copied to clipboard
`bun test`
Jest
describe()
- [x] describe(name, fn)
- [x] describe.each(table)(name, fn, timeout)
- [x] describe.only(name, fn)
- [ ] describe.only.each(table)(name, fn)
- [x] describe.skip(name, fn)
- [ ] describe.skip.each(table)(name, fn)
test()
- [x] test(name, fn, timeout)
- [ ] test.concurrent(name, fn, timeout)
- [ ] test.concurrent.each(table)(name, fn, timeout)
- [ ] test.concurrent.only.each(table)(name, fn)
- [ ] test.concurrent.skip.each(table)(name, fn)
- [x] test.each(table)(name, fn, timeout)
- [ ] test.failing(name, fn, timeout)
- [ ] test.failing.each(name, fn, timeout)
- [ ] test.only.failing(name, fn, timeout)
- [ ] test.skip.failing(name, fn, timeout)
- [x] test.only(name, fn, timeout)
- [ ] test.only.each(table)(name, fn)
- [x] test.skip(name, fn)
- [ ] test.skip.each(table)(name, fn)
- [x] test.todo(name)
Lifecycle hooks
- [x] afterAll(fn, timeout)
- [x] afterEach(fn, timeout)
- [x] beforeAll(fn, timeout)
- [x] beforeEach(fn, timeout)
expect()
- [x] expect(value)
- [x] expect.extend(matchers)
- [x] expect.anything()
- [x] expect.any(constructor)
- [x] expect.arrayContaining(array)
- [x] expect.assertions(number)
- [x] expect.closeTo(number, numDigits?)
- [x] expect.hasAssertions()
- [x] expect.not.arrayContaining(array)
- [x] expect.not.objectContaining(object)
- [x] expect.not.stringContaining(string)
- [x] expect.not.stringMatching(string | regexp)
- [x] expect.objectContaining(object)
- [x] expect.stringContaining(string)
- [x] expect.stringMatching(string | regexp)
- [ ] expect.addSnapshotSerializer(serializer)
- [x] .not
- [x] .resolves
- [x] .rejects
- [x] .toBe(value)
- [x] .toHaveBeenCalled()
- [x] .toHaveBeenCalledTimes(number)
- [x] .toHaveBeenCalledWith(arg1, arg2, ...)
- [x] .toHaveBeenLastCalledWith(arg1, arg2, ...)
- [x] .toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)
- [x] .toHaveReturned()
- [x] .toHaveReturnedTimes(number)
- [ ] .toHaveReturnedWith(value)
- [ ] .toHaveLastReturnedWith(value)
- [ ] .toHaveNthReturnedWith(nthCall, value)
- [x] .toHaveLength(number)
- [x] .toHaveProperty(keyPath, value?)
- [x] .toBeCloseTo(number, numDigits?)
- [x] .toBeDefined()
- [x] .toBeFalsy()
- [x] .toBeGreaterThan(number | bigint)
- [x] .toBeGreaterThanOrEqual(number | bigint)
- [x] .toBeLessThan(number | bigint)
- [x] .toBeLessThanOrEqual(number | bigint)
- [x] .toBeInstanceOf(Class)
- [x] .toBeNull()
- [x] .toBeTruthy()
- [x] .toBeUndefined()
- [x] .toBeNaN()
- [x] .toContain(item)
- [x] .toContainEqual(item)
- [x] .toEqual(value)
- [x] .toMatch(regexp | string)
- [x] .toMatchObject(object)
- [x] .toMatchSnapshot(propertyMatchers?, hint?)
- [x] .toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot)
- [x] .toStrictEqual(value)
- [x] .toThrow(error?)
- [x] .toThrowErrorMatchingSnapshot(hint?)
- [x] .toThrowErrorMatchingInlineSnapshot(inlineSnapshot)
Mocks
- [x] jest.fn(implementation?)
- [x] jest.mock(module)
- [ ] jest.requireActual(module)
- [x] jest.clearAllMocks
- [x] jest.resetAllMocks
- [x] jest.restoreAllMocks
- [x] mockFn.getMockName()
- [x] mockFn.mock.calls
- [x] mockFn.mock.results
- [x] mockFn.mock.instances
- [x] mockFn.mock.contexts
- [x] mockFn.mock.lastCall
- [x] mockFn.mockClear()
- [x] mockFn.mockReset()
- [x] mockFn.mockRestore()
- [x] mockFn.mockImplementation(fn)
- [x] mockFn.mockImplementationOnce(fn)
- [x] mockFn.mockName(name)
- [x] mockFn.mockReturnThis()
- [x] mockFn.mockReturnValue(value)
- [x] mockFn.mockReturnValueOnce(value)
- [x] mockFn.mockResolvedValue(value)
- [x] mockFn.mockResolvedValueOnce(value)
- [x] mockFn.mockRejectedValue(value)
- [x] mockFn.mockRejectedValueOnce(value)
- [x] mockFn.withImplementation(fn, callback)
Misc
- [x] jest.setTimeout
Vitest
expect()
Mocks
- [x] vi.fn
- [x] vi.mock
- [ ] vi.doMock
- [ ] vi.mocked
- [ ] vi.spyOn
- [ ] vi.unmock
- [ ] vi.importActual
- [ ] vi.importMock
- [ ] vi.resetAllMocks
- [ ] vi.dynamicImportSettled
- [ ] vi.resetModules
- [ ] vi.restoreAllMocks
- [ ] vi.stubEnv
- [ ] vi.unstubAllEnvs
- [ ] vi.stubGlobal
- [ ] vi.unstubAllGlobals
- [ ] vi.doUnmock
Timers
- [ ] vi.advanceTimersByTime
- [ ] vi.advanceTimersByTimeAsync
- [ ] vi.advanceTimersToNextTimer
- [ ] vi.advanceTimersToNextTimerAsync
- [ ] vi.getTimerCount
- [ ] vi.clearAllTimers
- [ ] vi.getMockedSystemTime
- [ ] vi.getRealSystemTime
- [ ] vi.restoreCurrentDate
- [ ] vi.runAllTicks
- [ ] vi.runAllTimers
- [ ] vi.runAllTimersAsync
- [ ] vi.runOnlyPendingTimers
- [ ] vi.runOnlyPendingTimersAsync
- [ ] vi.setSystemTime
- [ ] vi.useFakeTimers
- [ ] vi.useRealTimers
Misc
- [ ] vi.resetConfig
- [ ] vi.setConfig
jest-extended
expect()
- [x] .pass(message)
- [x] .fail(message)
- [x] .toBeEmpty()
- [x] .toBeOneOf([members])
- [x] .toBeNil()
- [x] .toBeArray()
- [x] .toBeArrayOfSize()
- [ ] .toIncludeAllMembers([members])
- [ ] .toIncludeAllPartialMembers([members])
- [ ] .toIncludeAnyMembers([members])
- [ ] .toIncludeSameMembers([members])
- [ ] .toPartiallyContain(member)
- [ ] .toSatisfyAll(predicate)
- [ ] .toSatisfyAny(predicate)
- [ ] .toBeInRange(min, max)
- [x] .toBeBoolean()
- [x] .toBeTrue()
- [x] .toBeFalse()
- [x] .toBeDate()
- [x] .toBeValidDate()
- [ ] .toBeAfter(date)
- [ ] .toBeBefore(date)
- [ ] .toBeAfterOrEqualTo(date)
- [ ] .toBeBeforeOrEqualTo(date)
- [ ] .toBeBetween(startDate, endDate)
- [x] .toBeFunction()
- [ ] .toThrowWithMessage()
- [ ] .toHaveBeenCalledBefore()
- [ ] .toHaveBeenCalledAfter()
- [ ] .toHaveBeenCalledOnce()
- [ ] .toHaveBeenCalledOnceWith()
- [x] .toBeNumber()
- [x] .toBeNaN()
- [x] .toBeFinite()
- [x] .toBePositive()
- [x] .toBeNegative()
- [x] .toBeEven()
- [x] .toBeOdd()
- [x] .toBeWithin(start, end)
- [x] .toBeInteger()
- [x] .toBeObject()
- [x] .toBeEmptyObject()
- [x] .toContainKey(key)
- [x] .toContainKeys([keys])
- [x] .toContainAllKeys([keys])
- [x] .toContainAnyKeys([keys])
- [x] .toContainValue(value)
- [x] .toContainValues([values])
- [x] .toContainAllValues([values])
- [x] .toContainAnyValues([values])
- [ ] .toContainEntry([key, value])
- [ ] .toContainEntries([[key, value]])
- [ ] .toContainAllEntries([[key, value]])
- [ ] .toContainAnyEntries([[key, value]])
- [ ] .toBeExtensible()
- [ ] .toBeFrozen()
- [ ] .toBeSealed()
- [ ] .toResolve()
- [ ] .toReject()
- [x] .toBeString()
- [ ] .toBeHexadecimal(string)
- [ ] .toBeDateString(string)
- [ ] .toEqualCaseInsensitive(string)
- [x] .toStartWith(prefix)
- [x] .toEndWith(suffix)
- [x] .toInclude(substring)
- [x] .toIncludeRepeated(substring, times)
- [ ] .toIncludeMultiple([substring])
- [x] .toEqualIgnoringWhitespace(string)
- [x] .toBeSymbol()
ts-jest does some magical hoisting with mock* functions which may or may not be a challenge with bun:
https://github.com/swc-project/swc/issues/5448#issuecomment-1386969864
This issue can be updated to check off these four (they were implemented in PR https://github.com/oven-sh/bun/pull/1573):
.toBeGreaterThan(number | bigint).toBeGreaterThanOrEqual(number | bigint).toBeLessThan(number | bigint).toBeLessThanOrEqual(number | bigint)
Should jest.mock be added as well? Doesn't seem to be tracked.
@erikshestopal please give it a try in the canary build, a lot of it is in there
jest.clearAllMocks() is also missing 👀 🙏
Would there be any scope to add DOM matchers? If so, I'd love for some parity with the jest-dom library.
toThrowError is missing. It's a alias for toThrow.
Ref: https://jestjs.io/docs/expect#tothrowerror
test.each and describe.each are super helpful to build data-driven unit tests.
I am proposing adding https://vitest.dev/api/expect-typeof.html to the vitest list.
test.eachanddescribe.eachare super helpful to build data-driven unit tests.
It's being worked on in PR #4047
Are there plans to add the expect.toBeInTheDocument matcher from @testing-library/jest-dom that many typically use for JSX component testing? Or is that out of scope? Feels like that would be something useful to provide out of the box.
expect.objectContaining
any ideas how to replace this call in tests?
Solution / Workaround
expect(Object.fromEntries(data.statistics[Kpi.codes])).toHaveProperty(`502`, 1)
expect(Object.fromEntries(data.statistics[Kpi.codes])).toHaveProperty(`200`, 32)
// instead of:
expect(Object.fromEntries(data.statistics[Kpi.codes])).toStrictEqual(
expect.objectContaining({ '200': 32, '502': 1 })
)
What can you recommend as a replacement for such jest code?
await expect(async () => await askGPT(text, prompt, context)).rejects.toThrowError(`⛔ API error.`)
Shouldn't that be working?
Does this suit your needs?
import { describe, expect, test } from 'bun:test';
const askGPT = async (text: string, prompt: string, context: string): Promise<void> => {
throw new Error('⛔ API error.');
};
describe('', () => {
test('', async () => {
await expect(async () => await askGPT('text', 'prompt', 'context')).toThrow(Error(`⛔ API error.`));
});
});
Edit: these functions have been added to the list, now, thank you!!
Should
jest.mockbe added as well? Doesn't seem to be tracked.
This still seems to not be on the list. Could we get support for jest.mock and jest.requireActual compatibility APIs added as an official target on this list? Module mocking is a pretty important part of jest compatibility.
Example:
import { foo } from 'some-module'
jest.mock('some-module', () => ({
...jest.requireActual<object>('some-module'),
foo: jest.fn(() => 'foo'),
}))
The pattern here allows you to override just the foo method of some-module, while requireActual gives you the real implementation for the rest.
Jest also supports placing an override for some-module in a __mocks__/some-module.ts file, as another way to automatically module-mock, though imho that is less priority.
Shouldn't that be working?
Does this suit your needs?
import { describe, expect, test } from 'bun:test'; const askGPT = async (text: string, prompt: string, context: string): Promise<void> => { throw new Error('⛔ API error.'); }; describe('', () => { test('', async () => { await expect(async () => await askGPT('text', 'prompt', 'context')).toThrow(Error(`⛔ API error.`)); }); });
This works only in bun, but not in vitest, so it's not compatible. It seems .rejects.toThrow is not implemented correctly or at all in bun, it throws Expected value must be a function on code like this that works in vitest:
await expect(asyncFn()).rejects.toThrow()
There is an issue on spyon https://github.com/oven-sh/bun/issues/4482
Would love to see these implemented:
test.concurrenttest.concurrent.eachtest.each
Even basic half-broken implementation of concurrent (like in jest) would be awesome, as it's absolutely vital for various slow integration tests involving external APIs and services. I'm saying half-broken because in jest before* and after* hooks don't work correctly with concurrent, but it's still usable - you can call the setup/teardown logic directly from each test.
Should
jest.mockbe added as well? Doesn't seem to be tracked.This still seems to not be on the list. Could we get support for
jest.mockandjest.requireActualcompatibility APIs added as an official target on this list? Module mocking is a pretty important part ofjestcompatibility.Example:
import { foo } from 'some-module' jest.mock('some-module', () => ({ ...jest.requireActual<object>('some-module'), foo: jest.fn(() => 'foo'), }))The pattern here allows you to override just the
foomethod ofsome-module, whilerequireActualgives you the real implementation for the rest.Jest also supports placing an override for
some-modulein a__mocks__/some-module.tsfile, as another way to automatically module-mock, though imho that is less priority.
Well put together @TroyAlford I think this is a very clear implementation maybe you want to create a new issue?
Are there plans to add the
expect.toBeInTheDocumentmatcher from@testing-library/jest-domthat many typically use for JSX component testing? Or is that out of scope? Feels like that would be something useful to provide out of the box.
Very much looking for information on this as well to be honest.
Could we get support for jest.mock and jest.requireActual compatibility APIs
Well put together @TroyAlford I think this is a very clear implementation maybe you want to create a new issue?
This has been added to the list above, now. Thank you!! :) As suggested by @coolxeo, I've also opened a new issue in relation for tracking the sub-task: https://github.com/oven-sh/bun/issues/5394.
Shouldn't that be working? Does this suit your needs?
import { describe, expect, test } from 'bun:test'; const askGPT = async (text: string, prompt: string, context: string): Promise<void> => { throw new Error('⛔ API error.'); }; describe('', () => { test('', async () => { await expect(async () => await askGPT('text', 'prompt', 'context')).toThrow(Error(`⛔ API error.`)); }); });This works only in bun, but not in vitest, so it's not compatible. It seems
.rejects.toThrowis not implemented correctly or at all in bun, it throwsExpected value must be a functionon code like this that works in vitest:await expect(asyncFn()).rejects.toThrow()
I have the exact same issue: it is not ISO from jest to bun. expect().rejects.toThrow breaks in bun while working in Jest.
Shouldn't that be working? Does this suit your needs?
import { describe, expect, test } from 'bun:test'; const askGPT = async (text: string, prompt: string, context: string): Promise<void> => { throw new Error('⛔ API error.'); }; describe('', () => { test('', async () => { await expect(async () => await askGPT('text', 'prompt', 'context')).toThrow(Error(`⛔ API error.`)); }); });This works only in bun, but not in vitest, so it's not compatible. It seems
.rejects.toThrowis not implemented correctly or at all in bun, it throwsExpected value must be a functionon code like this that works in vitest:await expect(asyncFn()).rejects.toThrow()I have the exact same issue: it is not ISO from jest to bun.
expect().rejects.toThrowbreaks in bun while working in Jest.
Same here, it seems like we cannot await on expect also
Are there plans to add the
expect.toBeInTheDocumentmatcher from@testing-library/jest-domthat many typically use for JSX component testing? Or is that out of scope? Feels like that would be something useful to provide out of the box.
I also need this feature for component testing
Are there plans to add the
expect.toBeInTheDocumentmatcher from@testing-library/jest-domthat many typically use for JSX component testing? Or is that out of scope? Feels like that would be something useful to provide out of the box.I also need this feature for component testing
i've asked a few times on their discord but nobodies been able to give any answer at all regarding this.
@riezahughes we will add support for expect.extend and get @testing-library/jest-dom to work
Another thing to consider for compatibility is the ability to configure custom file names to pick up: https://github.com/oven-sh/bun/discussions/5880
In jest you can do this with https://jestjs.io/docs/configuration#testregex-string--arraystring
@Jarred-Sumner @Electroid Hi, is there any roadmap or planned date of release for this missing features? Personally interested in concurrent tests, as it could speed up some tests significantly. By the way do you plan to create some sort of fixtures for tests? I think it is big pain point for a lot of people. Right now we use a workaround, but it would be nice to see it in standard bun testing library. P.S. by fixtures I mean some objects that are reused between tests and there is a ways for tuning its lifetime
@riezahughes we will add support for
expect.extendand get@testing-library/jest-domto work
This is the primary thing keeping us from adopting bun.
@riezahughes we will add support for
expect.extendand get@testing-library/jest-domto workThis is the primary thing keeping us from adopting bun.
This is also the only thing keeping us from adopting bun.