Skip to content

Restore mock.module using mock.restore not work as expect #7823

Open
@yukikwi

Description

@yukikwi

What version of Bun is running?

1.0.20+09d51486e

What platform is your computer?

Linux 6.5.0-14-generic x86_64 x86_64

What steps can reproduce the bug?

I create test file with this code inside

import axios from "axios"
import { describe, expect, it, mock } from "bun:test"

describe("topic", () => {
  it("test case 1", async () => {
    // before mock
    expect((await axios("https://google.com/", { method: "GET" })).status).toBe(200)

    // mock
    mock.module("axios", () => ({
      default: () => {
        return {
          status: 500
        } 
      }
    }));

    // after mock
    expect((await axios("https://google.com/", { method: "GET" })).status).toBe(500)

    // restore mock & test again
    mock.restore()
    expect((await axios("https://google.com/", { method: "GET" })).status).toBe(200)
  })
})

What is the expected behavior?

I expect this test case must pass

What do you see instead?

// before mock
expect((await axios("https://google.com/", { method: "GET" })).status).toBe(200) -> this pass

// after mock
expect((await axios("https://google.com/", { method: "GET" })).status).toBe(500) -> this pass

// restore mock & test again
expect((await axios("https://google.com/", { method: "GET" })).status).toBe(200) -> this fail (value is 500)

Additional information

This one work like what I expected but I think it is not good solution

import axios from "axios"
import path from "path"
import { describe, expect, it, mock } from "bun:test"

describe("topic", () => {
  it("test case 1", async () => {
    // before mock
    expect((await axios("https://google.com/", { method: "GET" })).status).toBe(200)

    // mock
    const axiosBak = axios  <-- add this
    mock.module("axios", () => ({
      default: () => {
        return {
          status: 500
        } 
      }
    }));

    // after mock
    expect((await axios("https://google.com/", { method: "GET" })).status).toBe(500)

    // restore mock & test again
    mock.restore()
    mock.module("axios", () => axiosBak) <-- add this
    expect((await axios("https://google.com/", { method: "GET" })).status).toBe(200)
  })
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingbun:testSomething related to the `bun test` runner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions