sinon#SinonSpy TypeScript Examples
The following examples show how to use
sinon#SinonSpy.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.spec.ts From css-render with MIT License | 6 votes |
describe('# mount & unmount with id (suite 2)', function () {
const style = c('.red-block', {
backgroundColor: 'red'
})
beforeEach(() => {
spy(console, 'error')
})
afterEach(() => {
(console.error as SinonSpy).restore()
style.unmount()
})
it('should mount same element with same id', function () {
const el = style.mount({
id: '14141'
})
const el2 = style.mount({
id: '14141'
})
expect(el).to.equal(el2)
})
})
Example #2
Source File: index.spec.ts From css-render with MIT License | 5 votes |
describe('# mount with no id', () => {
let sandbox: HTMLElement
const style = c('.red-block', {
backgroundColor: 'red'
})
before(() => {
style.mount()
sandbox = document.createElement('div')
document.body.appendChild(sandbox)
})
beforeEach(() => {
spy(console, 'error')
})
afterEach(() => {
(console.error as SinonSpy).restore()
sandbox.innerHTML = ''
})
it('should mount only once', () => {
expect(document.querySelectorAll('[cssr-id]').length).to.equal(1)
style.mount()
expect(document.querySelectorAll('[cssr-id]').length).to.equal(1)
})
it('should make element styled', () => {
sandbox.innerHTML = '<div class="red-block"></div>'
const backgroundColor = getComputedStyle(
sandbox.children[0]
).backgroundColor
expect(backgroundColor).to.equal('rgb(255, 0, 0)')
})
it('should support props of render', () => {
sandbox.innerHTML = '<sel1></sel1>'
const style = c('sel1', ({ props }) => {
return {
backgroundColor: props.color
}
})
style.mount({
props: {
color: 'red'
}
})
const backgroundColor = getComputedStyle(
sandbox.children[0]
).backgroundColor
expect(backgroundColor).to.equal('rgb(255, 0, 0)')
})
after(() => {
document.body.removeChild(sandbox)
style.unmount()
})
})
Example #3
Source File: index.spec.ts From css-render with MIT License | 5 votes |
describe('# mount & unmount with id (suite 1)', () => {
const style = c('.red-block', {
backgroundColor: 'red'
})
before(() => {
style.mount({
id: 'test-id-1'
})
style.mount({
id: 'test-id-2'
})
style.mount({
id: '14138'
})
style.mount({
id: '14139'
})
})
beforeEach(() => {
spy(console, 'error')
})
afterEach(() => {
(console.error as SinonSpy).restore()
})
it('should work in no-count mode', () => {
expect(exists('jjy')).to.eq(false)
style.mount({ id: 'jjy' })
expect(exists('jjy')).to.eq(true)
expect(document.head.querySelector('[cssr-id="jjy"]')).not.to.eq(null)
style.unmount({ id: 'jjy' })
expect(document.head.querySelector('[cssr-id="jjy"]')).to.eq(null)
})
it('should mount desired style element on head', () => {
expect(document.head.querySelector('[cssr-id="test-id-1"]')).not.to.equal(
null
)
expect(document.head.querySelector('[cssr-id="14138"]')).not.to.equal(null)
})
it('should do nothing when unmount with an not exist id', () => {
style.unmount({
id: 'letitbe'
})
expect(style.els.length).to.equal(4)
})
it('should unmount the desired style element', () => {
style.unmount({
id: 'test-id-1'
})
style.unmount({
id: '14138'
})
expect(document.head.querySelector('[cssr-id="test-id-1"]')).to.equal(null)
expect(document.head.querySelector('[cssr-id="test-id-2"]')).not.to.equal(
null
)
expect(document.head.querySelector('[cssr-id="14138"]')).to.equal(null)
expect(document.head.querySelector('[cssr-id="14139"]')).not.to.equal(null)
expect(style.els.length).to.equal(2)
})
it('should unmount all related styles elements', () => {
style.unmount()
expect(style.els.length).to.equal(0)
})
after(() => {
style.unmount()
})
})
Example #4
Source File: Extension-PostInstall.test.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
suite("GIVEN keybindings conflict", function () {
let promptSpy: SinonSpy;
let installStatusStub: SinonStub;
describeMultiWS(
"GIVEN initial install",
{
beforeHook: async () => {
installStatusStub = sinon
.stub(VSCodeUtils, "getInstallStatusForExtension")
.returns(InstallStatus.INITIAL_INSTALL);
promptSpy = sinon.spy(KeybindingUtils, "maybePromptKeybindingConflict");
},
noSetInstallStatus: true,
},
() => {
beforeEach(() => {
installStatusStub = sinon
.stub(
KeybindingUtils,
"getInstallStatusForKnownConflictingExtensions"
)
.returns([{ id: "dummyExt", installed: true }]);
});
afterEach(() => {
installStatusStub.restore();
});
after(() => {
promptSpy.restore();
});
test("THEN maybePromptKeybindingConflict is called", async () => {
expect(promptSpy.called).toBeTruthy();
});
}
);
describeMultiWS(
"GIVEN not initial install",
{
beforeHook: async () => {
promptSpy = sinon.spy(KeybindingUtils, "maybePromptKeybindingConflict");
},
},
() => {
beforeEach(() => {
installStatusStub = sinon
.stub(
KeybindingUtils,
"getInstallStatusForKnownConflictingExtensions"
)
.returns([{ id: "dummyExt", installed: true }]);
});
afterEach(() => {
installStatusStub.restore();
});
after(() => {
promptSpy.restore();
});
test("THEN maybePromptKeybindingConflict is not called", async () => {
expect(promptSpy.called).toBeFalsy();
});
}
);
});
Example #5
Source File: 01-match.spec.ts From Dimensions with MIT License | 4 votes |
describe('Testing Match Core', () => {
const paper = './tests/kits/js/normal/paper.js';
const rock = './tests/kits/js/normal/rock.js';
const botList = [rock, paper];
const rpsDesign = new RockPaperScissorsDesign('RPS');
const d = create(rpsDesign, {
activateStation: false,
observe: false,
id: '12345678',
loggingLevel: Logger.LEVEL.NONE,
defaultMatchConfigs: {
bestOf: 9,
storeErrorLogs: false,
},
});
describe('Test configurations', () => {
it('should be initialized correctly to the dimension defaults', async () => {
// create match goes to as far as running initalize functions
const match = await d.createMatch(botList);
const deeped = stripFunctions(deepCopy(d.configs.defaultMatchConfigs));
expect(match.configs).to.containSubset(deeped);
expect(match.results).to.equal(null);
});
});
describe('Test initialization', () => {
let match: Match;
let sandbox: SinonSandbox;
let designInitializeSpy: SinonSpy;
before(async () => {
sandbox = sinon.createSandbox();
designInitializeSpy = sandbox.spy(d.design, 'initialize');
match = await d.createMatch(botList);
});
it('should generate 2 agents for a 2 agent RPS match', () => {
expect(match.agents.length).to.equal(2);
});
it('should call initialization function of the design', () => {
expect(designInitializeSpy).to.callCount(1);
});
it('match should have ready status', () => {
expect(match.matchStatus).to.equal(Match.Status.READY);
});
});
const testRunStopMatch = async (match: Match) => {
expect(match.matchStatus).to.equal(Match.Status.READY);
match.run().catch(noop);
return new Promise<void>((res, rej) => {
setTimeout(async () => {
try {
expect(match.matchStatus).to.equal(Match.Status.RUNNING);
await match.stop();
expect(match.matchStatus).to.equal(Match.Status.STOPPED);
await match.resume();
expect(match.matchStatus).to.equal(Match.Status.RUNNING);
res();
} catch (err) {
rej(err);
}
await match.destroy();
}, 100);
});
};
describe('Test running', () => {
it('should run correctly', async () => {
const match = await d.createMatch(botList, {
bestOf: 9,
});
const results = await match.run();
expect(results.scores).to.eql({ '0': 0, '1': 9 });
});
it('should resume and stop correctly', async () => {
const match = await d.createMatch(botList, {
bestOf: 1001,
});
await testRunStopMatch(match);
});
it('should throw errors trying to stop/resume when not allowed', async () => {
const match = await d.createMatch(botList, {
bestOf: 1001,
});
expect(match.matchStatus).to.equal(Match.Status.READY);
await expect(match.resume()).to.be.rejectedWith(MatchWarn);
match.run().catch(noop);
const timer = () => {
return new Promise<void>((res, rej) => {
setTimeout(async () => {
try {
expect(match.matchStatus).to.equal(Match.Status.RUNNING);
await expect(match.resume()).to.be.rejectedWith(MatchWarn);
await match.stop();
await expect(match.stop()).to.be.rejectedWith(MatchWarn);
expect(match.matchStatus).to.equal(Match.Status.STOPPED);
await match.resume();
expect(match.matchStatus).to.equal(Match.Status.RUNNING);
res();
} catch (err) {
rej(err);
}
await match.destroy();
}, 100);
});
};
await timer();
});
});
describe('Test secureMode', () => {
it('should initialize correctly', async () => {
const match = await d.createMatch(botList, {
bestOf: 11,
secureMode: true,
});
for (const agent of match.agents) {
expect(agent.options.secureMode).to.equal(true);
}
expect(match.configs.secureMode).to.equal(true);
});
it('should run correctly', async () => {
const match = await d.createMatch(botList, {
bestOf: 11,
secureMode: true,
});
const results = await match.run();
expect(results.scores).to.eql({ '0': 0, '1': 11 });
});
it('should resume and stop correctly', async () => {
const match = await d.createMatch(botList, {
bestOf: 1001,
});
await testRunStopMatch(match);
});
});
describe('Test custom designs', () => {
let custom: Design;
let d: DimensionType;
before(() => {
custom = createCustomDesign();
d = create(custom, {
activateStation: false,
observe: false,
loggingLevel: Logger.LEVEL.NONE,
defaultMatchConfigs: {
storeErrorLogs: false,
},
});
});
it('should run correctly', async () => {
const results = await d.runMatch(botList);
expect(results).to.eql({
ranks: [
{ agentID: 0, rank: 1 },
{ agentID: 1, rank: 2 },
],
});
});
it('should resume and stop correctly', async () => {
const match = await d.createMatch(botList);
await testRunStopMatch(match);
});
});
after(() => {
d.cleanupMatches();
});
});
Example #6
Source File: Extension-PostInstall.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
/**
* This is for testing functionality that is only triggered when activating
* a workspace after installation
*/
suite("GIVEN Dendron plugin activation", function () {
let setInitialInstallSpy: sinon.SinonSpy;
let showTelemetryNoticeSpy: sinon.SinonSpy;
let mockHomeDirStub: sinon.SinonStub;
function stubDendronWhenNotFirstInstall() {
MetadataService.instance().setInitialInstall();
}
function stubDendronWhenFirstInstall(ctx: ExtensionContext) {
ctx.globalState.update(GLOBAL_STATE.VERSION, undefined);
MetadataService.instance().setMeta(
"welcomeClickedTime",
Time.now().toMillis()
);
}
function setupSpies() {
setInitialInstallSpy = sinon.spy(
MetadataService.instance(),
"setInitialInstall"
);
showTelemetryNoticeSpy = sinon.spy(AnalyticsUtils, "showTelemetryNotice");
}
async function afterHook() {
mockHomeDirStub.restore();
sinon.restore();
}
describe("AND WHEN not first install", () => {
describeMultiWS(
"AND WHEN activate",
{
preActivateHook: async () => {
mockHomeDirStub = TestEngineUtils.mockHomeDir();
stubDendronWhenNotFirstInstall();
setupSpies();
},
afterHook,
timeout: 1e4,
},
() => {
test("THEN set initial install not called", () => {
expect(setInitialInstallSpy.called).toBeFalsy();
});
test("THEN do not show telemetry notice", () => {
expect(showTelemetryNoticeSpy.called).toBeFalsy();
});
}
);
describeMultiWS(
"AND WHEN firstInstall not set for old user",
{
preActivateHook: async () => {
mockHomeDirStub = TestEngineUtils.mockHomeDir();
stubDendronWhenNotFirstInstall();
setupSpies();
// when check for first install, should be empty
MetadataService.instance().deleteMeta("firstInstall");
},
afterHook,
timeout: 1e5,
},
() => {
test("THEN set initial install called", () => {
expect(
setInitialInstallSpy.calledWith(
Time.DateTime.fromISO("2021-06-22").toSeconds()
)
).toBeTruthy();
});
test("THEN do not show telemetry notice", () => {
expect(showTelemetryNoticeSpy.called).toBeFalsy();
});
}
);
});
describe("AND WHEN first install", () => {
describeMultiWS(
"AND WHEN activate",
{
preActivateHook: async ({ ctx }) => {
mockHomeDirStub = TestEngineUtils.mockHomeDir();
setupSpies();
stubDendronWhenFirstInstall(ctx);
},
noSetInstallStatus: true,
timeout: 1e5,
},
() => {
test("THEN set initial install called", () => {
expect(setInitialInstallSpy.called).toBeTruthy();
});
test("THEN global version set", () => {
expect(MetadataService.instance().getGlobalVersion()).toNotEqual(
undefined
);
});
test("THEN show telemetry notice", () => {
expect(showTelemetryNoticeSpy.called).toBeTruthy();
});
this.afterAll(afterHook);
}
);
});
describe("AND WHEN secondary install on a fresh vscode instance", () => {
describeMultiWS(
"AND WHEN activate",
{
preActivateHook: async ({ ctx }) => {
mockHomeDirStub = TestEngineUtils.mockHomeDir();
// new instance, so fresh user-data. global storage is clean slate.
stubDendronWhenFirstInstall(ctx);
// but we have first install already recorded in metadata.
stubDendronWhenNotFirstInstall();
setupSpies();
},
afterHook,
timeout: 1e4,
noSetInstallStatus: true,
},
() => {
// we prevent this from happening in new vscode instances.
test("THEN set initial install is not called", () => {
expect(setInitialInstallSpy.called).toBeFalsy();
});
// but stil want to set this in the fresh globalStorage of the new vscode instance
test("THEN global version set", () => {
expect(MetadataService.instance().getGlobalVersion()).toNotEqual(
undefined
);
});
}
);
});
});
Example #7
Source File: Survey.test.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
suite("SurveyUtils", function () {
describe("showInitialSurvey", () => {
let homeDirStub: SinonStub;
let stateStub: SinonStub;
let surveySpy: SinonSpy;
describeMultiWS(
"GIVEN INITIAL_SURVEY_SUBMITTED is not set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
() => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves(undefined);
surveySpy = sinon.spy(SurveyUtils, "showInitialSurvey");
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
});
describe("AND initialSurveyStatus is not set", () => {
test("THEN showInitialSurvey is called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
expect(
MetadataService.instance().getMeta().initialSurveyStatus
).toEqual(undefined);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual(undefined);
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeTruthy();
});
});
describe("AND initialSurveyStatus is set to cancelled", () => {
test("THEN showInitialSurvey is called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
MetadataService.instance().setInitialSurveyStatus(
InitialSurveyStatusEnum.cancelled
);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual(undefined);
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeTruthy();
});
});
describe("AND initialSurveyStatus is set to submitted", () => {
test("THEN showInitialSurvey is not called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
MetadataService.instance().setInitialSurveyStatus(
InitialSurveyStatusEnum.submitted
);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual(undefined);
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
describeMultiWS(
"GIVEN INITIAL_SURVEY_SUBMITTED is set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
() => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves("submitted");
surveySpy = sinon.spy(SurveyUtils, "showInitialSurvey");
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
});
describe("AND initialSurveyStatus is not set", () => {
test("THEN metadata is backfilled AND showInitialSurvey is not called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
// metadata is not set yet, we expect this to be backfilled
expect(
MetadataService.instance().getMeta().initialSurveyStatus
).toEqual(undefined);
// global state is already set.
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual("submitted");
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeFalsy();
// metadata is backfilled.
expect(
MetadataService.instance().getMeta().initialSurveyStatus
).toEqual(InitialSurveyStatusEnum.submitted);
});
});
describe("AND initialSurveyStatus is set to submitted", () => {
test("THEN showInitialSurvey is not called", async () => {
const tutorialInitializer = new TutorialInitializer();
const ws = ExtensionProvider.getDWorkspace();
MetadataService.instance().setInitialSurveyStatus(
InitialSurveyStatusEnum.submitted
);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.INITIAL_SURVEY_SUBMITTED
)
).toEqual("submitted");
await tutorialInitializer.onWorkspaceOpen({ ws });
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
});
describe("showLapsedUserSurvey", () => {
let homeDirStub: SinonStub;
let stateStub: SinonStub;
let surveySpy: SinonSpy;
let infoMsgStub: SinonStub;
describeMultiWS(
"GIVEN LAPSED_USER_SURVEY_SUBMITTED is not set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
(ctx) => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves(undefined);
surveySpy = sinon.spy(SurveyUtils, "showLapsedUserSurvey");
infoMsgStub = sinon
.stub(vscode.window, "showInformationMessage")
.resolves({ title: "foo" });
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
infoMsgStub.restore();
});
describe("AND lapsedUserSurveyStatus is not set", () => {
test("THEN showLapsedUserSurvey is called", async () => {
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeTruthy();
});
});
describe("AND lapsedUserSurveyStatus is set to submitted", () => {
test("THEN showLapsedUserSurvey is not called", async () => {
MetadataService.instance().setLapsedUserSurveyStatus(
LapsedUserSurveyStatusEnum.submitted
);
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
describeMultiWS(
"GIVEN LAPSED_USER_SURVEY_SUBMITTED is set",
{
beforeHook: async () => {
await resetCodeWorkspace();
homeDirStub = TestEngineUtils.mockHomeDir();
},
},
(ctx) => {
after(() => {
homeDirStub.restore();
});
beforeEach(() => {
stateStub = sinon
.stub(StateService.instance(), "getGlobalState")
.resolves("submitted");
surveySpy = sinon.spy(SurveyUtils, "showLapsedUserSurvey");
infoMsgStub = sinon
.stub(vscode.window, "showInformationMessage")
.resolves({ title: "foo" });
});
afterEach(() => {
stateStub.restore();
surveySpy.restore();
infoMsgStub.restore();
});
describe("AND lapsedUserSurveyStatus is not set", () => {
test("THEN metadata is backfilled AND showLapsedUserSurvye is not called", async () => {
// metadata is not set yet, we expect this to be backfilled.
expect(
MetadataService.instance().getLapsedUserSurveyStatus()
).toEqual(undefined);
// global state is already set.
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.LAPSED_USER_SURVEY_SUBMITTED
)
).toEqual("submitted");
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeFalsy();
// metadata is backfilled.
expect(
MetadataService.instance().getLapsedUserSurveyStatus()
).toEqual(LapsedUserSurveyStatusEnum.submitted);
});
});
describe("AND lapsedUserSurveyStatus is set to submitted", () => {
test("THEN showLapsedUserSurvey is not called", async () => {
expect(
MetadataService.instance().getLapsedUserSurveyStatus()
).toEqual(LapsedUserSurveyStatusEnum.submitted);
expect(
await StateService.instance().getGlobalState(
GLOBAL_STATE.LAPSED_USER_SURVEY_SUBMITTED
)
).toEqual("submitted");
await StartupUtils.showLapsedUserMessage(
VSCodeUtils.getAssetUri(ctx)
);
await new Promise((resolve: any) => {
setTimeout(() => {
resolve();
}, 1);
});
expect(surveySpy.calledOnce).toBeFalsy();
});
});
}
);
});
});