Bun is a new runtime similar to Node.js, but optimized for performance and includes additional global objects and APIs, such as fetch and WebSocket. Jest is a widely used JavaScript testing framework that provides extensive mocking capabilities to help developers test their code.
Assume we need to mock a global object of Bun, such as fetch, which is commonly used in unit tests for API calls. Here are the steps to use Jest to mock this fetch global object:
Step 1: Set Up Jest Test Environment
First, ensure that Jest is installed in your project. If not, install it using npm or yarn:
bashnpm install --save-dev jest
or
bashyarn add --dev jest
Step 2: Create Test File
Create a test file in your project, such as fetch.test.js, where we will write test cases.
Step 3: Mock Global Objects
In Jest, we can use the global keyword to access global objects. To mock fetch, add the following code in Jest's test file or setup file:
javascript// fetch.test.js beforeAll(() => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({ data: 'some data' }), }) ); }); afterAll(() => { global.fetch.mockClear(); delete global.fetch; });
This code sets up the mock for the fetch method before all tests run and cleans up the mock after all tests complete.
Step 4: Write Test Cases
Next, we can write a test case using this mocked fetch method:
javascripttest('fetch data using global fetch', async () => { const response = await fetch('https://api.example.com/data'); const data = await response.json(); expect(data).toEqual({ data: 'some data' }); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledWith('https://api.example.com/data'); });
This test verifies that fetch is called correctly and returns the mocked data.
Step 5: Run Tests
Finally, run Jest to view the test results:
bashnpx jest fetch.test.js
If everything is configured correctly, you should see the test passing information.
Here is an example of how to use Jest to mock the global fetch object of Bun. Similar approaches can be applied to other global objects in the Bun environment. This technique is very useful for unit testing, especially when the code under test depends on external APIs or other global dependencies.