Skip to content

[Bug]: mock the imported function from another module (wildcard import) #578

@n0th1ng-else

Description

@n0th1ng-else

Version

System:
    OS: macOS 15.6
    CPU: (12) arm64 Apple M2 Pro
    Memory: 202.56 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Browsers:
    Chrome: 140.0.7339.133
    Safari: 18.6
  npmPackages:
    @rstest/core: 0.4.0 => 0.4.0

Details

I am playing with rstest in our app (we have ~50k tests). The challenge I am facing right now is that we used Jest and the code was downlevelled into CommonJS.

The common pattern is to use wildcard import import * as utilsModule from './utils', This would generate both getter and setter for each exported function.

Now with rstest I assume it is esm, hence it only generates the getter for the export. So the spyOn mock like rstest.spyOn(utilsModule, 'isPerformanceStep') throws Cannot redefine property: isPerformanceStep
I tried to adjust the swc config and tell it to transform to commonjs, but have to luck. I also tried to adjust the swc config in the rstest.config.js as well, does not work for me. Any advice here?

Reproduce link

described in the repro steps

Reproduce Steps

Default (empty) rstest config. Then:

// util.ts

export const sayHi = () => 'hi';

and the test

// util.spec.ts

import {rstest,expect, it} from '@rstest/core';
import * as utils from './util'

const spy = rstest.spyOn(utils, 'sayHi');

it ('Check the result', ()=> {
    expect(utils.sayHi()).toBe('hi');
})

Run the test, see

TypeError: Cannot redefine property: sayHi

  2 | import * as utils from './util'
  3 |
> 4 | const spy = rstest.spyOn(utils, 'sayHi');

the utils oject look like this

import * as utils from './util'

utils -> Object [Module] { sayHi: [Getter] }

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions