-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
bun test
#1825
Comments
|
This issue can be updated to check off these four (they were implemented in PR #1573):
|
Should |
@erikshestopal please give it a try in the canary build, a lot of it is in there |
Would there be any scope to add DOM matchers? If so, I'd love for some parity with the jest-dom library. |
|
|
I am proposing adding https://vitest.dev/api/expect-typeof.html to the vitest list. |
It's being worked on in PR #4047 |
Are there plans to add the |
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.`));
});
}); |
@cpt-westphalen Step 6 shouldn't be necessary to do manually. Those types should come out-of-the-box with the library. The same PR that fixed the types for But again, this is not the place to hash out these issues. Any bugs or gaps in |
Sorry for flooding here with that. I may replace it with the link to the discussion in jest-dom if you prefer. |
thanks @cpt-westphalen, I was able to fix the warning with your solution! |
Not sure if I'm missing something, but #5356 is still happening for me on 1.1.3 |
Anyone here get the actual matchers working but run into an issue where
|
I was facing the same issue where |
This is great thank you! I think this is the perfect place to add these instructions. They are extremely necessary to make bun test work with extra matchers that most people are already using and are migrating to bun test now.
|
On my end I was also getting the error 'Multiple elements found' and I added this to my beforeEach(() => {
document.body.innerHTML = '';
}) I still run into the same error as @paulleonartcalvo with |
For me it is very important to have With these two I guess that I could plan a PoC at work. Do you have a roadmap / expectations to have these two done? |
@paulleonartcalvo @immayurpanchal @hussain-s6 @srosato everyone that has the |
@rbwestphalen My tests that fail with this error have no problem passing with jest and jsdom. I will try to dig more into it when I get a chance |
Temporary implementation for == testSetup.ts == import { expect as bunExpect, mock as originalMock } from 'bun:test';
// Define the type for the original mock function
type OriginalMockFunction = (...args: unknown[]) => unknown;
// Define the type for our extended mock function
type ExtendedMockFunction = OriginalMockFunction & {
callOrder: number[];
originalMock: OriginalMockFunction;
};
// Create an extended mock function
function createMock(): ExtendedMockFunction {
const original = originalMock() as OriginalMockFunction;
const mockFunction = ((...args: unknown[]) => {
mockFunction.callOrder.push(++createMock.callOrderCounter);
return original(...args);
}) as ExtendedMockFunction;
mockFunction.callOrder = [] as number[];
mockFunction.originalMock = original;
return mockFunction;
}
createMock.callOrderCounter = 0;
// Custom matchers
function toHaveBeenCalledBefore(
this: { utils: any },
received: ExtendedMockFunction,
secondMock: ExtendedMockFunction,
) {
const firstCallOrder = received.callOrder[0];
const secondCallOrder = secondMock.callOrder[0];
if (firstCallOrder < secondCallOrder) {
return {
pass: true,
message: () =>
`Expected ${received.originalMock.name} to have been called before ${secondMock.originalMock.name}`,
};
} else {
return {
pass: false,
message: () =>
`Expected ${received.originalMock.name} to have been called before ${secondMock.originalMock.name}, but it was called after`,
};
}
}
function toHaveBeenCalledAfter(
this: { utils: any },
received: ExtendedMockFunction,
firstMock: ExtendedMockFunction,
) {
const firstCallOrder = firstMock.callOrder[0];
const secondCallOrder = received.callOrder[0];
if (secondCallOrder > firstCallOrder) {
return {
pass: true,
message: () =>
`Expected ${received.originalMock.name} to have been called after ${firstMock.originalMock.name}`,
};
} else {
return {
pass: false,
message: () =>
`Expected ${received.originalMock.name} to have been called after ${firstMock.originalMock.name}, but it was called before`,
};
}
}
// Custom matchers interface
interface CustomMatchers<T = unknown, R = void> {
toHaveBeenCalledAfter(firstMock: T): R;
toHaveBeenCalledBefore(secondMock: T): R;
}
// Ensure the custom matchers interface extends the Bun matchers interface with consistent type parameters
declare module 'bun:test' {
interface Matchers<T = unknown, R = void> extends CustomMatchers<T, R> {}
}
// Add custom matchers to expect
const expectWithMatchers = bunExpect as typeof bunExpect & {
extend: (
matchers: Record<
string,
(
this: { utils: any },
...args: any[]
) => { pass: boolean; message: () => string }
>,
) => void;
};
// Add custom matchers to expect
expectWithMatchers.extend({ toHaveBeenCalledBefore, toHaveBeenCalledAfter });
// Override the mock function in bun:test
const bunTest = require('bun:test');
bunTest.mock = createMock; == order.test.ts == import './testSetup';
import { describe, expect, it, mock } from 'bun:test';
describe('Function Call Order Tests', () => {
it('should call initialize before process', () => {
const initialize = mock();
const process = mock();
// Simulate the function calls
initialize();
process();
// Verify the call order
expect(initialize).toHaveBeenCalledBefore(process);
});
it('should call finalize after process', () => {
const process = mock();
const finalize = mock();
// Simulate the function calls
process();
finalize();
// Verify the call order
expect(finalize).toHaveBeenCalledAfter(process);
});
it('should call fetchData before processData', () => {
const fetchData = mock();
const processData = mock();
// Simulate the function calls
fetchData();
processData();
// Verify the call order
expect(fetchData).toHaveBeenCalledBefore(processData);
});
it('should call saveData after processData', () => {
const processData = mock();
const saveData = mock();
// Simulate the function calls
processData();
saveData();
// Verify the call order
expect(saveData).toHaveBeenCalledAfter(processData);
});
it('should call setup before execute and then cleanup', () => {
const setup = mock();
const execute = mock();
const cleanup = mock();
// Simulate the function calls
setup();
execute();
cleanup();
// Verify the call order
expect(setup).toHaveBeenCalledBefore(execute);
expect(execute).toHaveBeenCalledBefore(cleanup);
});
}); == Preload == |
|
Don't know where/how to report this, but as Bun is focused so much on performance and the docs have statements like "Running 266 React SSR tests faster than Jest can print its version number." I can only imagine I run into some problem/bug. I was finally able to run tests of an existing project in Bun instead of Jest and Bun takes ~36.1s while Jest needs ~12.8s. It's a bit hard to create a minimal example, but I use happydom and Testing Library. Is this result expected? What are realistic numbers? |
@donaldpipowitch That is definitely not expected. Would love to be able to profile your test suite and see what's going on. If you're unable to send code for us to look at, if you're on a mac you could try:
Instruments comes with Xcode. It'll look something like this: |
Thanks for the quick response. As this is likely a bug then (or bigger misconfiguration from my side) I'll try to create a minimal test case. |
@Jarred-Sumner Stupid question, but could it simply be the case that bun is not parallelizing the tests? I tried to break it down, but it becomes less obvious if you run single tests (for single tests bun is a bit faster).
|
bun does run all tests single-threaded, but often the cost of parallelizing tests is so high that it doesn't end up being a performance win to use threads is it using timers? we haven't implemented fake timers yet, and IIRC, the testing library code does something like wait 500 milliseconds of IRL wall clock time in certain cases when there's no jest fake timers |
We don't run |
@Jarred-Sumner , sorry to bother you, I was just curious if you got the |
dang... no toBeInTheDocument... what the heck bun... |
Hey folks, just a follow up on my comment from a few months ago. One of our contributors figured out the differences between bun test and jest, specifically:
Which was breaking assumptions we had from running Jest and trying to use I think this was mostly consumer error on our end, I don't think Bun needs to change, but I thought it might be helpful to leave some breadcrumbs here in case you're also running into issues swapping But with this change, we're finally realizing 20x improvements on test suite speed. Phenomenal. Huge. So worth it. |
Re-tested it with |
To clarify @simylein's request — this is about type checker tests for TypeScript, not Haven't seen it added to the master list yet, so here I am raising my hand as well 👋 |
I'm really missing a |
Indeed, it's quite unexpected for globals to live across tests. Would expect each test (i.e each test file) to start with a clean global slate. Imho, seems just too easy to forget cleaning up something that trips up a subsequent test, and may not even be possible for third party libs. If this is indeed the intended behavior, it's probably different enough from how other test frameworks behave to warrant its documentation. |
Jest
describe()
test()
Lifecycle hooks
expect()
Mocks
Misc
Vitest
expect()
Mocks
Timers
Misc
jest-extended
expect()
The text was updated successfully, but these errors were encountered: