chai#expect JavaScript Examples
The following examples show how to use
chai#expect.
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: test.js From Path-Finding-Visualizer with MIT License | 6 votes |
test = (input, output, opts, done) => {
postcss([
plugin(opts)
])
.process(input, { from: '<inline>' })
.then(result => {
expect(result.css).to.eql(output);
expect(result.warnings()).to.be.empty; // eslint-disable-line no-unused-expressions
done();
})
.catch(done);
}
Example #2
Source File: user-home.spec.js From Changes with MIT License | 6 votes |
describe('UserHome', () => {
let userHome
beforeEach(() => {
userHome = shallow(<UserHome email="[email protected]" />)
})
it('renders the email in an h3', () => {
expect(userHome.find('h3').text()).to.be.equal('Welcome, [email protected]')
})
})
Example #3
Source File: checkColorProp.js From beautiful-react-ui with MIT License | 6 votes |
checkColorProp = (Component, defaultProps = {}, options = defaultOptions, elementQuery = null) => {
const opts = { ...defaultOptions, ...options };
const query = elementQuery || '* > *';
it('should allow to change color', () => {
const props = {
...defaultProps,
[opts.colorProp]: opts.defaultColor,
};
const { container, rerender } = render(<Component {...props} />);
const nodeEl = container.querySelector(query);
expect(nodeEl.classList.contains(opts.defaultColorClass)).to.be.true;
const nextProps = { [opts.colorProp]: opts.checkColor };
rerender(<Component {...nextProps} />);
expect(nodeEl.classList.contains(opts.checkColorClass)).to.be.true;
expect(nodeEl.classList.contains(opts.defaultColorClass)).to.be.false;
});
}
Example #4
Source File: HelloWorld.spec.js From SecureCloudStorageVue with MIT License | 6 votes |
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = shallow(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).to.include(msg)
})
})
Example #5
Source File: register.spec.js From SSO_Project with GNU General Public License v3.0 | 6 votes |
describe("Register (View)", () => {
it("loads proper default values", () => {
expect(wrapper.vm.$data.token).to.equal("");
expect(wrapper.vm.$data.error).to.equal(0);
expect(wrapper.vm.$data.agreeToC).to.equal(false);
expect(wrapper.vm.$data.success).to.equal(null);
expect(activateWrapper.vm.$data.token).to.equal("12345");
});
it("forwards registration request", async () => {
expect(apiPost.calledWith("/local/register")).to.equal(false);
wrapper.vm.submit();
await wrapper.vm.$nextTick();
expect(apiPost.calledWith("/local/register")).to.equal(true);
expect(wrapper.vm.$data.success).to.equal(true);
});
it("forwards activation request", async () => {
expect(apiPost.calledWith("/local/activate")).to.equal(false);
activateWrapper.vm.submit();
await activateWrapper.vm.$nextTick();
expect(apiPost.calledWith("/local/activate")).to.equal(true);
expect(setLoginToken.calledWith("username")).to.equal(true);
expect(routerPush.calledWith("/audit")).to.equal(true);
});
});
Example #6
Source File: app.swipe.steps.js From webdriverio-appium-cucumber-boilerplate with Apache License 2.0 | 6 votes |
Then(
/^o app exibe o card com o nthCard '(.+)' e o texto '(.+)'$/,
(nthCard, Text) => {
const expectedText = Text.toLowerCase();
const cardText = SwipeScreen.carousel.getCardText(nthCard);
if (driver.isIOS) {
return expect(cardText).contain(expectedText);
}
/**
* Needed to implement this for Android because the `flex:wrap` returns an incorrect order
* of the text so we need to split words and verify then
*/
return expectedText
.split(' ')
.forEach((word) => expect(cardText).contain(word));
},
);
Example #7
Source File: generic-client-engine.spec.js From talk-control with Apache License 2.0 | 6 votes |
describe('GenericEngine', function() {
describe('constructor()', function() {
it('should have instantiated GenericEngine', function() {
stub(window, 'addEventListener');
const engine = new GenericEngine();
window.addEventListener.restore();
expect(engine).to.be.ok;
});
});
});
Example #8
Source File: index.test.js From schema-plugin-flow with MIT License | 6 votes |
describe('===============model init empty schema=================', () => {
let mApi = null;
let namespace = 'test01',
refreshApi = (callback) => { callback() },
externals = { initValue: 'value' },
components = {},
modelApiRef = (api) => { console.log('mapi ref'); mApi = api; },
modelOptions = {
externals,
components,
modelApiRef,
};
const sifoModel = new SifoModel(
namespace,
refreshApi,
{},// schema
[],//plugins,
modelOptions);
sifoModel.run();
let schemaNode = mApi.getSchema();
it('should count correctly', () => {
expect(mApi).to.be.a('object');
console.log('empty schema', JSON.stringify(schemaNode));
// empty setAttributes
mApi.setAttributes('test', 'a');
const a = mApi.getAttributes('test');
expect(a).to.equal(undefined);
// getExternals
const externals = mApi.getExternals();
expect(externals.initValue).to.equal('value');
})
});
Example #9
Source File: index.js From Learning-Redux with MIT License | 6 votes |
describe('isCheerioTask', () => {
it('should return true for actions that are Cheerio tasks', () => {
const actionObj = {
type: 'CHEERIO_TASK',
payload: {
url: 'http://www.example.com',
task: () => null
}
};
expect(isCheerioTask(actionObj)).to.be.true;
});
it('should return false for actions that are not Cheerio tasks', () => {
const actionObj = {};
expect(isCheerioTask(actionObj)).to.be.false;
expect(isCheerioTask(defaultPendingAction)).to.be.false;
})
});
Example #10
Source File: example.spec.js From certd with MIT License | 6 votes |
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = shallowMount(HelloWorld, {
props: { msg }
})
expect(wrapper.text()).to.include(msg)
})
})
Example #11
Source File: apiError.js From checkout-sdk-node with MIT License | 6 votes |
describe('Handling Errors', () => {
const mockErrorResponse = { error: true };
const mockErrorCode = 500;
afterEach(() => {
nock.cleanAll();
});
it('should handle API error', async() => {
nock('https://api.sandbox.checkout.com')
.post('/tokens')
.reply(mockErrorCode, mockErrorResponse);
const cko = new Checkout();
cko.config.pk = PK;
let errorWasThrown = false;
try {
await cko.tokens.request({
type: 'card',
number: '4242424242424242',
expiry_month: 6,
expiry_year: 2029,
cvv: '100'
});
} catch(error) {
errorWasThrown = true;
expect(error.http_code).to.equal(mockErrorCode);
expect(error.body).to.deep.equal(mockErrorResponse);
}
expect(errorWasThrown).to.equal(true);
});
});
Example #12
Source File: SizeSlider.js From mapapps-sketching-enhanced with Apache License 2.0 | 6 votes |
describe(module.id, function () {
it("validateInput gives defined Minimum with NaN input", function () {
const vm = new Vue(SizeSlider);
vm.min = 2;
expect(vm._validateInput('Test')).to.be.equal(2);
});
it("validateInput gives defined Minimum with input smaller than Minimum", function () {
const vm = new Vue(SizeSlider);
vm.min = 10;
expect(vm._validateInput('5')).to.be.equal(10);
});
it("validateInput gives defined Maximum with input bigger than Maximum", function () {
const vm = new Vue(SizeSlider);
vm.max = 2;
expect(vm._validateInput('5')).to.be.equal(2);
});
it("validateInput gives defined Minimum with empty input string", function () {
const vm = new Vue(SizeSlider);
vm.min = 2;
expect(vm._validateInput('')).to.be.equal(2);
});
it("validateInput returns given value as Integer with input in expected range", function () {
const vm = new Vue(SizeSlider);
vm.min = 1;
vm.max = 10;
expect(vm._validateInput('5')).to.be.equal(5);
});
});
Example #13
Source File: indexeddb.test.js From skeletor with MIT License | 6 votes |
describe('Collection using IndexedDB', function() {
const TestCollection = Collection.extend({
'browserStorage': new Storage('Collection', 'indexed'),
'model': Model
});
it('saves to localForage', async function () {
const collection = new TestCollection();
await new Promise((resolve, reject) => collection.fetch({success: () => resolve()}));
const model = await new Promise((resolve, reject) => collection.create({'hello': 'world!'}, {'success': resolve}));
const id = model.get('id');
expect(id).to.be.a('string');
expect(model.get('hello')).to.equal('world!')
});
it('removes from localForage', async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({'hello': 'world!'}, {'success': resolve}));
const store = model.collection.browserStorage;
const stored_model = await localForage.getItem(store.getItemName(model.id));
expect(stored_model).to.deep.equal(model.attributes);
expect(collection.length).to.equal(1);
const stored_collection = await localForage.getItem(store.name);
await new Promise((resolve, reject) => collection.get(model.id).destroy({'success': resolve}));
expect(collection.length).to.equal(0);
expect(await localForage.getItem(store.getItemName(model.id))).to.be.null;
// expect collection references to be reset
const stored_collection2 = await localForage.getItem(store.name);
expect(stored_collection2.length).to.equal(stored_collection.length - 1);
});
});
Example #14
Source File: example.spec.js From ddosgrid-v2 with Apache License 2.0 | 6 votes |
describe('BarChart.vue', () => {
global.fetch = async () => {
return {
json: async () => {
return {
topTen: [
{
count: 1,
port: 1
}
]
}
}
}
}
it('Accepts a dataset as a property', () => {
const wrapper = shallowMount(HelloWorld, {
propsData: { url: '123' }
})
expect(wrapper.props().url).to.equal('123')
})
})
Example #15
Source File: StopStart.js From binary-bot with MIT License | 6 votes |
describe('Run Interpreter over bot', () => {
let value;
beforeAll(done => {
let interpreter = createInterpreter();
interpreter.run(
`
(function (){
${parts.tickTrade}
while(watch('before')) {}
})();
`
);
setTimeout(() => {
interpreter.stop();
interpreter = createInterpreter();
interpreter
.run(
`
(function (){
${parts.tickTrade}
${parts.waitToPurchase}
${parts.waitToSell}
return true;
})();
`
)
.then(v => {
value = v;
done();
});
}, 8000);
});
it('Code block is executed correctly', () => {
expect(value).to.be.equal(true);
});
});
Example #16
Source File: test.js From spring-boot-ecommerce with Apache License 2.0 | 6 votes |
test = (input, output, opts, done) => {
postcss([
plugin(opts)
])
.process(input, { from: '<inline>' })
.then(result => {
expect(result.css).to.eql(output);
expect(result.warnings()).to.be.empty; // eslint-disable-line no-unused-expressions
done();
})
.catch(done);
}
Example #17
Source File: Layout.test.js From light-blue-react-template with MIT License | 6 votes |
describe('Layout', () => {
it('renders children correctly', () => {
const store = mockStore(initialState);
const wrapper = render(
<App context={{ insertCss: () => {}, store }}>
<Layout>
<div className="child" />
</Layout>
</App>,
);
expect(wrapper.find('div.child').length).to.eq(1);
});
});
Example #18
Source File: GelatoGasPriceOracle.deployment.test.js From gelato-network with MIT License | 6 votes |
describe("GelatoCore - GelatoGasPriceOracle - Deployment", function () {
// We define the ContractFactory and Signer variables here and assign them in
// a beforeEach hook.
let GelatoGasPriceOracleFactory;
let gelatoGasPriceOracle;
let owner;
let ownerAddress;
before(async function () {
// Get the ContractFactory, contract instance, and Signers here.
GelatoGasPriceOracleFactory = await ethers.getContractFactory(
"GelatoGasPriceOracle"
);
gelatoGasPriceOracle = await GelatoGasPriceOracleFactory.deploy(
initialState.gasPrice
);
await gelatoGasPriceOracle.deployed();
[owner] = await ethers.getSigners();
ownerAddress = await owner.getAddress();
});
// We test different functionality of the contract as normal Mocha tests.
it("Should initialize only the creation time state variables", async function () {
expect(await gelatoGasPriceOracle.owner()).to.equal(ownerAddress);
expect(await gelatoGasPriceOracle.oracle()).to.equal(ownerAddress);
expect(await gelatoGasPriceOracle.latestAnswer()).to.be.equal(
initialState.gasPrice
);
});
});
Example #19
Source File: example.spec.js From wine-launcher with GNU General Public License v3.0 | 6 votes |
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).to.include(msg)
})
})
Example #20
Source File: LoadingIndicator.spec.js From sqliteviz with Apache License 2.0 | 6 votes |
describe('LoadingIndicator.vue', () => {
it('Calculates animation class', async () => {
const wrapper = shallowMount(LoadingIndicator, {
propsData: { progress: 0 }
})
expect(wrapper.find('svg').classes()).to.contain('progress')
await wrapper.setProps({ progress: undefined })
expect(wrapper.find('svg').classes()).to.not.contain('progress')
expect(wrapper.find('svg').classes()).to.contain('loading')
})
it('Calculates arc', async () => {
const wrapper = shallowMount(LoadingIndicator, {
propsData: { progress: 50 }
})
// The lendth of circle in the component is 50.24. If progress is 50% then resulting arc
// should be 25.12
expect(wrapper.find('.loader-svg.front').element.style.strokeDasharray)
.to.equal('25.12px, 25.12px')
})
})
Example #21
Source File: stub.test.js From test-automation-training with MIT License | 6 votes |
describe('sinon.stub 使用示例', () => {
it('sinon.stub 直接调用返回匿名函数', () => {
const stub = sinon.stub();
stub('hello');
expect(stub.firstCall.args).to.deep.equal(['hello']);
});
it('sinon.stub 替换对象函数并设置行为', () => {
const stub = sinon.stub();
// 预设行为,stub函数调用返回值为54
stub.returns(54);
expect(stub()).to.equal(54);
});
it('sinon.stub 替换对象函数并模拟实际调用的函数', () => {
const myObj = {};
myObj.prop = function propFn() {
return 'foo';
};
// 对myObj的prop方法进行预设行为,当调用这个方法的时候实际会调用fakeFn这个函数
sinon.stub(myObj, 'prop').callsFake(function fakeFn() {
return 'bar';
});
expect(myObj.prop()).to.equal('bar');
});
});
Example #22
Source File: test.js From geoserver-node-client with BSD 2-Clause "Simplified" License | 6 votes |
describe('Basic GeoServer', () => {
it('should exist', async () => {
const result = await grc.about.exists();
expect(result).to.be.true;
});
it('returns correct version', async () => {
const result = await grc.about.getVersion();
expect(result.about.resource[0].Version).to.equal(geoServerVersion);
})
});
Example #23
Source File: test.js From NevtMD-V2 with MIT License | 5 votes |
describe('Encryptions', () => {
describe('Base64', () => {
it('From string to base64', done => {
try {
const res = toBase64('Hello World!!');
expect(res).to.be.a('string');
expect(res).to.be.equal('SGVsbG8gV29ybGQhIQ==');
return done();
}
catch (e) {
return done(e);
}
});
it('from base64 to string', done => {
try {
const res = fromBase64ToString('SGVsbG8gV29ybGQhIQ==');
expect(res).to.be.a('string');
expect(res).to.be.equal('Hello World!!');
return done();
}
catch (e) {
return done(e);
}
});
});
describe('Crypto', () => {
it('randomUUID', done => {
try {
const res = randomUUID();
expect(res).to.be.a('string');
return done();
}
catch (e) {
return done(e);
}
});
it('randomBytes', done => {
try {
const res = randomBytes(16);
expect(res).to.be.a('string');
return done();
}
catch (e) {
return done(e);
}
});
it('createHash', done => {
try {
const res = createHash('sha256', 'Hello world!!');
expect(res).to.be.a('string');
expect(res).to.have.length(64);
return done();
}
catch (e) {
return done(e);
}
});
});
});
Example #24
Source File: auditlog.spec.js From SSO_Project with GNU General Public License v3.0 | 5 votes |
describe("AuditLog (Component)", () => {
it("has proper default values", () => {
expect(wrapper.vm.$data.activeAccordion).to.equal("");
expect(wrapper.vm.$data.auditPage).to.equal(0);
expect(wrapper.vm.$data.loading).to.equal(false);
expect(wrapper.emitted("ready").length).to.equal(1);
});
it("can expand and collapse accordion", () => {
expect(wrapper.vm.$data.activeAccordion).to.equal("");
wrapper.get("button.btn").trigger("click");
expect(wrapper.vm.$data.activeAccordion).to.not.equal("");
wrapper.get("button.btn").trigger("click");
expect(wrapper.vm.$data.activeAccordion).to.equal("");
});
it("loads log entries", async () => {
expect(wrapper.vm.$data.auditLogs).to.be.an("array").and.has.lengthOf(5);
expect(apiGet.calledWith("/audit/logs?page=0")).to.equal(true);
expect(wrapper.emitted("reload")).to.equal(undefined);
wrapper.get("#loadMoreAudit").trigger("click");
await wrapper.vm.$nextTick();
expect(wrapper.vm.$data.auditLogs).to.be.an("array").and.has.lengthOf(10);
expect(wrapper.emitted("reload").length).to.equal(1);
});
it("closes session", async () => {
apiPost.resetHistory();
wrapper.get("#closeSessions").trigger("click");
await wrapper.vm.$nextTick();
expect(apiPost.calledWith("/local/session-clean")).to.equal(true);
expect(wrapper.vm.$data.auditLogs).to.be.an("array").and.has.lengthOf.most(5);
});
it("reports suspicious log entry", async () => {
apiPost.resetHistory();
wrapper.get(".report-log").trigger("click");
await wrapper.vm.$nextTick();
expect(apiPost.calledWith("/local/session-clean")).to.equal(true);
expect(apiPost.calledWith("/audit/report")).to.equal(true);
});
});
Example #25
Source File: app.forms.steps.js From webdriverio-appium-cucumber-boilerplate with Apache License 2.0 | 5 votes |
When(/^o botão de switch está desabilitado$/, () => {
expect(FormScreen.isSwitchActive()).to.equal(false);
});
Example #26
Source File: revealjs-client-engine.spec.js From talk-control with Apache License 2.0 | 5 votes |
describe('RevealEngineClient', function() {
let engine;
beforeEach(function() {
window.Reveal = {
getCurrentSlide: stub(),
configure: spy(),
next: spy(),
up: spy(),
down: spy(),
left: spy(),
right: spy(),
slide: spy(),
getIndices: stub(),
addEventListener: spy(),
getSlides: stub()
};
stub(window, 'addEventListener');
stub(window.parent, 'postMessage');
engine = new RevealEngine();
});
afterEach(function() {
window.addEventListener.restore();
window.parent.postMessage.restore();
});
describe('constructor()', function() {
it('should have instantiated RevealEngine', function() {
expect(engine).to.be.ok;
});
});
describe('goToSlide()', function() {
it('should call Reveal.slide() with the given params', function() {
// Given
stub(engine, 'getSlides').returns([
{ h: 1, v: 1, f: -1, fMax: -1 },
{ h: 1, v: 2, f: -1, fMax: 4 }
]);
// When
engine.goToSlide({ h: 1, v: 2, f: 3 });
// Then
assert(window.Reveal.slide.calledOnceWith(1, 2, 3));
});
});
describe('getSlides()', function() {
it('should return an array of slides', function() {
// Given
const querySelectorAll = stub().returns([]);
stub(document, 'querySelectorAll').returns([{ querySelectorAll }, { querySelectorAll }, { querySelectorAll }]);
// When
const slides = engine.getSlides();
// Then
expect(slides.length).to.equals(3);
expect(slides[0]).to.eqls({ h: 0, v: 0, f: -1, fMax: -1 });
document.querySelectorAll.restore();
});
});
});
Example #27
Source File: weakee.spec.js From PeerWebSite with GNU General Public License v3.0 | 5 votes |
describe('weakee', function() {
var entity
beforeEach(()=>{
class UserClass extends Emitter {
constructor() {
super()
}
}
entity = new UserClass();
})
it('should allow to emit events', function() {
entity.emit('test')
entity.emit('test2')
})
it('should call listeners when events are emitted, with the arguments as emitted', function(done){
entity.on('test', (arg1, arg2)=>{
expect(arg1).to.equal('a')
expect(arg2).to.equal(null)
done()
})
setTimeout(function(){
entity.emit('test', 'a', null)
}, 10);
})
it('should be able to unregister a listener', function(done){
function listener() {
throw new Error('listener must not get called')
}
entity.on('test', listener)
entity.off('test', listener)
setTimeout(function(){
entity.emit('test', 'a', null)
done()
}, 10)
})
it('should register after one event has been fired when using "once"', function(done){
entity.once('test', (arg1, arg2)=>{
expect(arg1).to.equal('a')
expect(arg2).to.equal(null)
})
setTimeout(function(){
entity.emit('test', 'a', null)
entity.emit('test', 'not gonna trigger that listener')
done()
}, 10)
})
})
Example #28
Source File: index.test.js From schema-plugin-flow with MIT License | 5 votes |
describe('import', () => {
it('should import correctly', () => {
expect(formCoreModelPlugin).to.not.eql(undefined);
});
});
Example #29
Source File: prediction.js From ml-classify-text-js with MIT License | 5 votes |
describe('Prediction', () => {
describe('constructor', () => {
it('should throw an error if prediction is not an object literal', () => {
expect(() => new Prediction([])).to.throw(Error)
})
})
describe('label', () => {
it('should throw an error if label is not a string', () => {
const prediction = new Prediction()
expect(() => {
prediction.label = []
}).to.throw(Error)
})
it('should return a string', () => {
const prediction = new Prediction()
expect(prediction.label).to.be.a('string')
})
it('should return the defined prediction label', () => {
const prediction = new Prediction({
label: 'test'
})
expect(prediction.label).to.equal('test')
})
it('should set the prediction label', () => {
const prediction = new Prediction()
prediction.label = 'test'
expect(prediction.label).to.equal('test')
})
})
describe('confidence', () => {
it('should throw an error if confidence is not a number', () => {
const prediction = new Prediction()
expect(() => {
prediction.confidence = 'test'
}).to.throw(Error)
})
it('should return a number', () => {
const prediction = new Prediction()
expect(prediction.confidence).to.be.a('number')
})
it('should return the defined prediction confidence', () => {
const prediction = new Prediction({
confidence: 0.5
})
expect(prediction.confidence).to.equal(0.5)
})
it('should set the prediction confidence', () => {
const prediction = new Prediction()
prediction.confidence = 1
expect(prediction.confidence).to.equal(1)
})
})
})