Promise.withResolvers() implementation / mocks #5512
-
Hello, I've been trying to use Promise.WithResolvers in my repository, but when I ran the tests I got // with spyOn (Error: withResolvers does not exist)
vi.spyOn(window.Promise.prototype, 'withResolvers').mockImplementation(() => {
let resolve, reject
const promise = new Promise((res, rej) => { resolve = res, reject = rej })
return { promise, resolve, reject }
})
// with mock (TypeError: Cannot read properties of undefined (reading 'replace'))
vi.mock(window.Promise.withResolvers, () => {
let resolve, reject
const promise = new Promise((res, rej) => { resolve = res, reject = rej })
return { promise, resolve, reject }
}) I am guessing spyOn isn't going to work since it only works on functions that already exists.
Is there any way currently to mock |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The feature like I'm not sure whether "mocking" is relevant for your use case, but I think typically people would simply monkey-patch (i.e. polyfill) non-existing global. Have you tried something like this? Promise.withResolvers = () => {
let resolve, reject
const promise = new Promise((res, rej) => { resolve = res, reject = rej })
return { promise, resolve, reject }
} If you want to "spy" its function calls, then you could probably do: import { vi } from "vitest"
Promise.withResolvers = vi.fn(() => {
// ... same thing here ...
}); Note that |
Beta Was this translation helpful? Give feedback.
The feature like
Promise.withResolvers
is simply a runtime feature and it's not something "Vitest implements". As seen at the bottom of the same MDN page, it looks like Node simply doesn't have it yet.I'm not sure whether "mocking" is relevant for your use case, but I think typically people would simply monkey-patch (i.e. polyfill) non-existing global. Have you tried something like this?
If you want to "spy" its function calls, then you could probably do: