|
| 1 | +import { Org } from '@salesforce/core'; |
| 2 | + |
| 3 | +import sinon = require('sinon'); |
| 4 | +import { expect } from '@salesforce/command/lib/test'; |
| 5 | +import { Connection, ExecuteAnonymousResult } from 'jsforce'; |
| 6 | +import { AnonymousApexRunner } from '../../../../src/utils/apex/executor/AnonymousApexRunner'; |
| 7 | + |
| 8 | +describe('AnonymusApexRunner', () => { |
| 9 | + let org: Org; |
| 10 | + let sandboxStub: sinon.SinonSandbox; |
| 11 | + |
| 12 | + beforeEach(async () => { |
| 13 | + sandboxStub = sinon.createSandbox(); |
| 14 | + const getConnectionStub = sandboxStub.stub().returns({ |
| 15 | + tooling: { |
| 16 | + executeAnonymous: () => {}, |
| 17 | + }, |
| 18 | + } as unknown as Connection); |
| 19 | + sandboxStub.stub(Org.prototype, 'getConnection').callsFake(getConnectionStub); |
| 20 | + org = new Org({}); |
| 21 | + }); |
| 22 | + |
| 23 | + afterEach(() => { |
| 24 | + sandboxStub.restore(); |
| 25 | + }); |
| 26 | + |
| 27 | + it('should run anonymous Apex correctly', async () => { |
| 28 | + const anonymousApex = "System.debug('Hello, World');"; |
| 29 | + const expectedResponse = { success: true }; |
| 30 | + |
| 31 | + const executeAnonymousResultStub = sandboxStub |
| 32 | + .stub() |
| 33 | + .returns(Promise.resolve({ success: true } as unknown as ExecuteAnonymousResult)); |
| 34 | + sandboxStub.stub(Org.prototype.getConnection().tooling, 'executeAnonymous').callsFake(executeAnonymousResultStub); |
| 35 | + |
| 36 | + const result = await AnonymousApexRunner.run(org, anonymousApex); |
| 37 | + |
| 38 | + expect(result).to.deep.equal(expectedResponse); |
| 39 | + sinon.assert.calledOnce(executeAnonymousResultStub); |
| 40 | + sinon.assert.calledWith(executeAnonymousResultStub, anonymousApex); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should handle executeAnonymous errors', async () => { |
| 44 | + const anonymousApex = "System.debug 'Hello, World');"; |
| 45 | + const executeAnonymousError = new Error('Error executing anonymous Apex'); |
| 46 | + const executeAnonymousResultStub = sandboxStub.stub().rejects(executeAnonymousError); |
| 47 | + sandboxStub.stub(Org.prototype.getConnection().tooling, 'executeAnonymous').callsFake(executeAnonymousResultStub); |
| 48 | + |
| 49 | + try { |
| 50 | + await AnonymousApexRunner.run(org, anonymousApex); |
| 51 | + throw new Error('Test should have thrown an error'); |
| 52 | + } catch (error) { |
| 53 | + expect(error).to.equal(executeAnonymousError); |
| 54 | + sinon.assert.calledOnce(executeAnonymousResultStub); |
| 55 | + sinon.assert.calledWith(executeAnonymousResultStub, anonymousApex); |
| 56 | + } |
| 57 | + }); |
| 58 | +}); |
0 commit comments