|
8 | 8 |
|
9 | 9 | /* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */ |
10 | 10 |
|
| 11 | +import * as util from 'util'; |
11 | 12 | import vm, {Context} from 'vm'; |
12 | 13 | import {ModuleMocker, fn, mocked, spyOn} from '../'; |
13 | 14 |
|
@@ -1073,6 +1074,62 @@ describe('moduleMocker', () => { |
1073 | 1074 | }); |
1074 | 1075 | }); |
1075 | 1076 |
|
| 1077 | + describe('withImplementation', () => { |
| 1078 | + it('sets an implementation which is available within the callback', () => { |
| 1079 | + const mock1 = jest.fn(); |
| 1080 | + const mock2 = jest.fn(); |
| 1081 | + |
| 1082 | + const Module = jest.fn(() => ({someFn: mock1})); |
| 1083 | + const testFn = function () { |
| 1084 | + const m = new Module(); |
| 1085 | + m.someFn(); |
| 1086 | + }; |
| 1087 | + |
| 1088 | + Module.withImplementation( |
| 1089 | + () => ({someFn: mock2}), |
| 1090 | + () => { |
| 1091 | + testFn(); |
| 1092 | + expect(mock2).toHaveBeenCalled(); |
| 1093 | + expect(mock1).not.toHaveBeenCalled(); |
| 1094 | + }, |
| 1095 | + ); |
| 1096 | + |
| 1097 | + testFn(); |
| 1098 | + expect(mock1).toHaveBeenCalled(); |
| 1099 | + |
| 1100 | + expect.assertions(3); |
| 1101 | + }); |
| 1102 | + |
| 1103 | + it('returns a promise if the provided callback is asynchronous', async () => { |
| 1104 | + const mock1 = jest.fn(); |
| 1105 | + const mock2 = jest.fn(); |
| 1106 | + |
| 1107 | + const Module = jest.fn(() => ({someFn: mock1})); |
| 1108 | + const testFn = function () { |
| 1109 | + const m = new Module(); |
| 1110 | + m.someFn(); |
| 1111 | + }; |
| 1112 | + |
| 1113 | + const promise = Module.withImplementation( |
| 1114 | + () => ({someFn: mock2}), |
| 1115 | + async () => { |
| 1116 | + testFn(); |
| 1117 | + expect(mock2).toHaveBeenCalled(); |
| 1118 | + expect(mock1).not.toHaveBeenCalled(); |
| 1119 | + }, |
| 1120 | + ); |
| 1121 | + |
| 1122 | + expect(util.types.isPromise(promise)).toBe(true); |
| 1123 | + |
| 1124 | + await promise; |
| 1125 | + |
| 1126 | + testFn(); |
| 1127 | + expect(mock1).toHaveBeenCalled(); |
| 1128 | + |
| 1129 | + expect.assertions(4); |
| 1130 | + }); |
| 1131 | + }); |
| 1132 | + |
1076 | 1133 | test('mockReturnValue does not override mockImplementationOnce', () => { |
1077 | 1134 | const mockFn = jest |
1078 | 1135 | .fn() |
|
0 commit comments