-
Notifications
You must be signed in to change notification settings - Fork 2.5k
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.`));
});
}); |
I really really would love to have pub var is_expecting_assertions: bool = false;
pub var is_expecting_assertions_count: bool = false; seems to be using global state to handle some functionality, which is written to when calling Are there any plans to rework this in the future? I feel that async tests would greatly benefit from a concurrent-enabled runner. In the future a parallel-enabled runner would even benefit sync tests. |
@dylan-conway, @Electroid There seems to be a disconnect on what is implemented between your docs and this issue tracker. For example, |
@Jarred-Sumner Any updates on this one? I was looking at |
We added |
@Jarred-Sumner Thanks for the super fast reply! I saw that Here's an example that says "Property 'toBeInTheDocument' does not exist on type 'Matchers'":
What's the missing piece for the setup to use happy-dom expect methods together with buns |
@sebastianbuechler The |
@jakeboone02 Thanks for pointing this out. You're of course right, it's from So just to be clear, if I want to use
|
@sebastianbuechler Yes, that should work. TypeScript shouldn't complain either, but if it does then file an issue with |
The same test.
But Is it much harder to implement than |
jest.setTimeout is missing as well. If it is not needed then please explain how to make tests work both with node+jest and bun? Is there some global constant exists to check if this is jest or bun environment? |
Is test context in the scope? That's so useful! |
@sebastianbuechler did you manage to make it work without Typescript complaining? To me is working after exending jest-dom matchers, but seems not to extend the type and Typescript outputs: |
@fjpedrosa this should be reported in the |
@fjpedrosa & @jakeboone02 Just half way. I wanted to define it in a setup function so that I don't have to repeat it, but it seems that typescript does not recognize it that way. I abandoned bun test as it seems just not mature enough if you have already a lot of tests working with vitest and DOM expectations. Maybe better documentation would help here. |
I did it. It works. I'm not experienced at configuring stuff, as you may notice by it, but I kept thinking: if someone's smart enough to code the thing I should be at least smart enough to find out how to use it, lol. Anyway, for anyone who falls here and needs to know how to configure bun with happy-dom and jest-dom with TypeScript and working code completion, that is how I did it in Vite for working with React: How to configure Bun + Jest-DOM + Happy DOM in Vite (TypeScript React)
"types": [
"bun-types", // add Bun global
"@testing-library/react", // if with react
"@testing-library/jest-dom",
"web"
],
import { GlobalRegistrator } from "@happy-dom/global-registrator";
const oldConsole = console;
GlobalRegistrator.register();
window.console = oldConsole;
import * as matchers from "@testing-library/jest-dom/matchers";
import { expect } from "bun:test";
// Extend the expect object with custom matchers
expect.extend(matchers); It is ugly, I know. It works, so I'm not touching it again so soon.
If you want to place the happydom file somewhere else, just make sure it is being parsed by TypeScript.
import "@testing-library/jest-dom";
import type { TestingLibraryMatchers } from "@testing-library/jest-dom/matchers";
declare module "bun:test" {
interface Matchers<R = void>
extends TestingLibraryMatchers<
typeof expect.stringContaining,
R
> {}
interface AsymmetricMatchers
extends TestingLibraryMatchers {}
}
|
@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 == |
Tracking issues to change
bun wiptest
tobun test
.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: