You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
+ const { value } = await import('./some/module.js')
938
938
```
939
939
940
+
<<<<<<< HEAD
940
941
运行 `vitest` 时,可以使用 `vi.hoisted` 方法自动完成此操作。
942
+
=======
943
+
When running `vitest`, you can do this automatically by using `vi.hoisted` method. Under the hood, Vitest will convert static imports into dynamic ones with preserved live-bindings.
Running code before the imports means that you cannot access imported variables because they are not defined yet:
957
+
958
+
```ts
959
+
import { value } from'./some/module.js'
960
+
961
+
vi.hoisted(() => { value }) // throws an error // [!code warning]
962
+
```
963
+
964
+
This code will produce an error:
965
+
966
+
```
967
+
Cannot access '__vi_import_0__' before initialization
968
+
```
969
+
970
+
If you need to access a variable from another module inside of `vi.hoisted`, use dynamic import:
971
+
972
+
```ts
973
+
awaitvi.hoisted(async () => {
974
+
const { value } =awaitimport('./some/module.js')
975
+
})
976
+
```
977
+
978
+
However, it is discourage to import anything inside of `vi.hoisted` because imports are already hoisted - if you need to execute something before the tests are running, just execute it in the imported module itself.
979
+
:::
980
+
981
+
This method returns the value that was returned from the factory. You can use that value in your `vi.mock` factories if you need easy access to locally defined variables:
> Configuring the server with `onUnhandledRequest: 'error'` ensures that an error is thrown whenever there is a request that does not have a corresponding request handler.
0 commit comments