Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions e2e/spy/fixtures/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const sayHi = () => 'hi';
39 changes: 39 additions & 0 deletions e2e/spy/spyOn.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, expect, it, rstest } from '@rstest/core';
import * as utils from './fixtures/util';

describe('test spyOn', () => {
it('spyOn', () => {
Expand Down Expand Up @@ -39,4 +40,42 @@ describe('test spyOn', () => {
spy.mockRestore();
expect(rstest.isMockFunction(hi.sayHi)).toBeFalsy();
});

it('spyOn import', () => {
expect(() => {
// @ts-expect-error test
utils.sayHi = () => 'hello';
}).toThrowError(
'Cannot set property sayHi of #<Object> which has only a getter',
);

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

expect(utils.sayHi()).toBe('hi');

expect(utils.sayHi).toBeCalled();

spy.mockImplementation(() => 'hello');

expect(utils.sayHi()).toBe('hello');

spy.mockReset();

expect(utils.sayHi()).toBe('hi');
});

it('spyOn dynamic import', async () => {
const util1 = await import('./fixtures/util');
const spy = rstest.spyOn(util1, 'sayHi');

expect(util1.sayHi()).toBe('hi');
expect(util1.sayHi).toBeCalled();

spy.mockImplementation(() => 'hello');

expect(util1.sayHi()).toBe('hello');

spy.mockReset();
expect(util1.sayHi()).toBe('hi');
});
});
11 changes: 11 additions & 0 deletions packages/core/src/core/plugins/mockRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ class MockRuntimeRspackPlugin {
);
module.source!.source = Buffer.from(finalSource);
}

if (module.name === 'define_property_getters') {
const finalSource = module.source!.source.toString('utf-8').replace(
// Sets the object configurable so that imported properties can be spied
// Hard coded in EJS template https://github.com/web-infra-dev/rspack/blob/main/crates/rspack_plugin_runtime/src/runtime_module/runtime/define_property_getters.ejs
'enumerable: true, get:',
'enumerable: true, configurable: true, get:',
);

module.source!.source = Buffer.from(finalSource);
}
},
);
});
Expand Down
Loading