chai#assert JavaScript Examples

The following examples show how to use chai#assert. 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: helpers.js    From mesconseilscovid with MIT License 6 votes vote down vote up
export async function waitForPlausibleTrackingEvents(page, names) {
    try {
        await page.waitForFunction(
            (events) =>
                window.app &&
                window.app._plausibleTrackingEvents &&
                window.app._plausibleTrackingEvents.length === events.length &&
                window.app._plausibleTrackingEvents.every(
                    (val, index) => val === events[index]
                ),
            names,
            { timeout: 2000 }
        )
    } catch (e) {
        assert.deepEqual(await getPlausibleTrackingEvents(page), names)
    }
}
Example #2
Source File: getAllForRestaurant.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
// Testing /reservation/?restaurantID GET endpoint. Using IDs 1-5

before(async () => {
  // Setup the database before any tests in this file run.
  const errors = [];
  await connection
    .asyncQuery('INSERT INTO RESTAURANT VALUES (1, "Example restaurant0");')
    .then(({ error }) => error && errors.push(error));

  await connection
    .asyncQuery(`INSERT INTO \`TABLE\` VALUES (1, 1, 1, 6);`)
    .then(({ error }) => error && errors.push(error));

  await connection
    .asyncQuery(
      `INSERT INTO USER VALUES (1, "First name", "Last name", "09 123,456", "[email protected]");`
    )
    .then(({ error }) => error && errors.push(error));
  assert.strictEqual(errors.length, 0, 'Expected no errors in initial setup');
});
Example #3
Source File: app.forms.steps.js    From webdriverio-appium-cucumber-boilerplate with Apache License 2.0 6 votes vote down vote up
Then(/^é exibido o texto que foi digitado$/, () => {
    assert.equal(
        FormScreen.inputTextResult.getText(),
        'Text for the type test',
    );

    /**
     * IMPORTANT!!
     *  Because the app is not closed and opened between the tests
     *  (and thus is NOT starting with the keyboard hidden)
     *  the keyboard is closed here if it is still visible.
     */
    if (driver.isKeyboardShown()) {
        driver.hideKeyboard();
    }
});
Example #4
Source File: tc-component.spec.js    From talk-control with Apache License 2.0 6 votes vote down vote up
describe('TCComponent', function() {
    let tcComponent;
    let on, broadcast;
    beforeEach(function() {
        tcComponent = new TCComponent({ engineName: 'revealjs' });
        on = stub(tcComponent.controllerComponentChannel, 'on');
        broadcast = stub(tcComponent.controllerComponentChannel, 'broadcast');
    });

    describe('constructor()', function() {
        it('should have instantiated TCServer', function() {
            expect(tcComponent).to.be.ok;
        });
    });

    describe('init()', function() {
        it('should do the required subscriptions', function() {
            // When
            tcComponent.init();
            // Then
            assert(on.calledWith('gotoSlide'), '"on" not called with gotoSlide');
            assert(broadcast.calledWith('initialized'), '"broadcast" not called with initialized');
        });
    });
});
Example #5
Source File: test-json.js    From ipfs-action with MIT License 6 votes vote down vote up
function verifyEncodedForm(testCase) {
  const obj = JSON.parse(testCase);
  const encoded = encode(obj);
  assert.strictEqual(new TextDecoder().decode(encoded), JSON.stringify(obj));
  const decoded = decode(encoded);
  assert.deepStrictEqual(decoded, obj);
  const decoded2 = decode(toBytes(testCase));
  assert.deepStrictEqual(decoded2, obj);
}
Example #6
Source File: localStorage.test.js    From skeletor with MIT License 6 votes vote down vote up
describe("Without browserStorage", function () {
    beforeEach(() => localStorage.clear());

    describe("on a Collection", function () {

        it("should use `ajaxSync`", function () {
            const TestCollection = Collection.extend();
            const collection = new TestCollection();
            const method = getSyncMethod(collection);
            assert.equal(method, sync);
        });
    });

    describe("on a Model", function () {

        it("should use `ajaxSync`", function () {
            const TestModel = Model.extend();
            const model = new TestModel();
            const method = getSyncMethod(model);
            assert.equal(method, sync);
        });
    });
});
Example #7
Source File: test-incomplete.js    From cbor-x with MIT License 6 votes vote down vote up
suite('encode and decode tests with partial values', function () {
  const encoder = new Encoder({ objectMode: true, structures: [] })

  for (const [label, testData] of Object.entries(tests)) {
    test(label, () => {
      const encoded = encoder.encode(testData)
      assert.isTrue(Buffer.isBuffer(encoded), 'encode returns a Buffer')
      assert.deepStrictEqual(encoder.decode(encoded, encoded.length, true), testData, 'full buffer decodes well')
      const firstHalf = encoded.slice(0, Math.floor(encoded.length / 2))
      let value
      try {
        value = encoder.decode(firstHalf, firstHalf.length, true)
      } catch (err) {
        if (err.incomplete !== true) {
          assert.fail(`Should throw an error with .incomplete set to true, instead threw error <${err}>`)
        } else {
          return; // victory! correct outcome!
        }
      }
      assert.fail(`Should throw an error with .incomplete set to true, instead returned value ${JSON.stringify(value)}`)
    })
  }
})
Example #8
Source File: test-incomplete.js    From msgpackr with MIT License 6 votes vote down vote up
suite('encode and decode tests with partial values', function () {
  const encoder = new Encoder({ objectMode: true, structures: [], moreTypes: true, structuredClone: true })

  for (const [label, testData] of Object.entries(tests)) {
    test(label, () => {
      const encoded = encoder.encode(testData)
      assert.isTrue(Buffer.isBuffer(encoded), 'encode returns a Buffer')
      assert.deepStrictEqual(encoder.decode(encoded, encoded.length, true), testData, 'full buffer decodes well')
      for (let length = Math.max(1, Math.ceil(encoded.length / 2) - 40); length < Math.ceil(encoded.length / 2); length++) {
        const firstHalf = encoded.slice(0, length)
        let value
        try {
          value = encoder.decode(firstHalf, firstHalf.length, true)
        } catch (err) {
          if (err.incomplete !== true) {
            assert.fail(`Should throw an error with .incomplete set to true, instead threw error <${err}>, for ${JSON.stringify(testData)} ${encoded.length}, ${length}`)
          } else {
            continue; // victory! correct outcome!
          }
        }
        assert.fail(`Should throw an error with .incomplete set to true, instead returned value ${JSON.stringify(value)}`)
      }
    })
  }
})
Example #9
Source File: api.test.js    From paypresto.js with Apache License 2.0 6 votes vote down vote up
describe('api.get()', () => {
  beforeEach(() => {
    nock('https://www.paypresto.co')
      .get('/api/ok')
      .once()
      .reply(200, '{"success": "ok"}', {
        'Content-Type': 'application/json'
      })

    nock('https://www.paypresto.co')
      .get('/api/err')
      .once()
      .reply(400, '{"error": "err"}', {
        'Content-Type': 'application/json'
      })
  })

  it('should respond when successful', () => {
    return api.get('/ok')
      .then(res => assert.equal(res.success, 'ok'))
      .catch(err => { throw err })
  })

  it('should reject when unsuccessful', () => {
    return api.get('/err')
      .then(_res => { throw new Error('was supposed to reject') })
      .catch(err => assert.equal(err.error, 'err'))
  })
})
Example #10
Source File: useFakeTimers.test.js    From test-automation-training with MIT License 6 votes vote down vote up
describe('sinon.useFakeTimers 使用示例', () => {
    it('sinon.useFakeTimers 模拟setTimeout和nextTick', () => {
        const clock = sinon.useFakeTimers({
            now: 1483228800000,
            toFake: ['setTimeout', 'nextTick']
        });

        let called = false;

        process.nextTick(function () {
            called = true;
        });

        setTimeout(() => {
            return true;
        }, 1000);

        clock.runAll(); //forces nextTick calls to flush synchronously
        assert(called);
    });
});
Example #11
Source File: 01_testIntroJSI.js    From practica_dwec_gestor_presupuesto with GNU General Public License v3.0 6 votes vote down vote up
// Función actualizarPresupuesto
describe("Función actualizarPresupuesto", function() {
    it("Actualiza presupuesto con valor válido", function() {
        assert.equal(actualizarPresupuesto(1000), 1000);
        assert.equal(actualizarPresupuesto(2050.25), 2050.25);
    });

    it("Devuelve -1 si el valor no es un número positivo", function() {
        assert.equal(actualizarPresupuesto(-1000), -1);
        assert.equal(actualizarPresupuesto(-150.42), -1);
        assert.equal(actualizarPresupuesto("blabla"), -1);
        assert.equal(actualizarPresupuesto({}), -1);
    });

});
Example #12
Source File: getStrategy.test.js    From redis-oplog with MIT License 6 votes vote down vote up
describe('Processors - Guess Strategy', function () {
    it('should work', function () {
        assert.equal(Strategy.DEFAULT, getStrategy({isFiltered: true}));
        assert.equal(Strategy.DEFAULT, getStrategy({isFiltered: true}, {sort: {createdAt: -1}}));

        assert.equal(Strategy.DEDICATED_CHANNELS, getStrategy({
            _id: 'STRING'
        }));

        assert.equal(Strategy.DEDICATED_CHANNELS, getStrategy({
            _id: {$in: []}
        }));

        assert.equal(Strategy.LIMIT_SORT, getStrategy({
            _id: {$in: []}
        }, {
            limit: 100,
            sort: {
                createdAt: -1
            }
        }));

        assert.equal(Strategy.LIMIT_SORT, getStrategy({}, {
            limit: 100,
            sort: {
                createdAt: -1
            }
        }));
    })
});
Example #13
Source File: util-tests.js    From albedo with MIT License 6 votes vote down vote up
describe('utilities tests', function () {
    before(() => {
        frontendStub.setup()
    })

    it('generates new random token each time', function () {
        const rnd = new Set(),
            iterations = 20
        for (let i = 0; i < iterations; i++) {
            rnd.add(intentLib.generateRandomToken())
        }
        assert.equal(rnd.size, iterations, 'Non-unique value detected')
    })

    it('manages implicit sessions', function () {
        const now = new Date().getTime(),
            expiration = [now, now - 1000000, now + 100000, now + 10000000]

        function formatPubkey(ts) {
            return 'pubkey' + ts
        }

        for (let ts of expiration) {
            saveImplicitSession({
                session: intentLib.generateRandomToken(),
                pubkey: formatPubkey(ts),
                grants: 'tx,pay',
                valid_until: ts
            })
        }

        let activeSessions = intentLib.listImplicitSessions()

        assert.equal(activeSessions.length, 2, 'Invalid expiration storage rules applied')

        assert.isTrue(intentLib.isImplicitSessionAllowed('tx', formatPubkey(expiration[3])))

        assert.isFalse(intentLib.isImplicitSessionAllowed('trust', formatPubkey(expiration[3])))

        assert.isFalse(intentLib.isImplicitSessionAllowed('tx', formatPubkey(expiration[1])))

        intentLib.forgetImplicitSession(formatPubkey(expiration[3]))

        activeSessions = intentLib.listImplicitSessions()

        assert.equal(activeSessions.length, 1)

        assert.equal(activeSessions[0].pubkey, formatPubkey(expiration[2]))
    })
})
Example #14
Source File: test.thematiques.js    From mesconseilscovid with MIT License 5 votes vote down vote up
describe('Thématiques', function () {
    it('titre de la page', async function () {
        const page = this.test.page

        await page.goto('http://localhost:8080/conseils-pour-les-enfants.html')

        assert.equal(
            await page.title(),
            'Conseils pour mon\u00a0enfant — Mes Conseils Covid'
        )
    })

    it('version dans le footer', async function () {
        const page = this.test.page

        await page.goto('http://localhost:8080/conseils-pour-les-enfants.html')
        const footer = await page.waitForSelector('footer')
        assert.include(await footer.innerText(), '- Mise à jour le ')
    })

    it('on va vers une autre page thématique', async function () {
        const page = this.test.page

        let messages = recordConsoleMessages(page)
        await page.goto('http://localhost:8080/conseils-pour-les-enfants.html')

        await Promise.all([
            page.click(
                '.thematiques a >> text="Passe sanitaire, que faut-il savoir\u00a0?"'
            ),
            page.waitForNavigation({
                url: '**/pass-sanitaire-qr-code-voyages.html',
            }),
        ])

        await waitForPlausibleTrackingEvent(
            page,
            'pageview:pass-sanitaire-qr-code-voyages.html'
        ),
            assert.lengthOf(messages, 3)
        assert.include(messages[0], {
            n: 'pageview',
            u: 'http://localhost/conseils-pour-les-enfants.html',
        })
        assert.include(messages[1], {
            n: 'Navigue vers une thématique depuis une autre thématique',
            p: '{"chemin":"/conseils-pour-les-enfants.html → /pass-sanitaire-qr-code-voyages.html"}',
            u: 'http://localhost/conseils-pour-les-enfants.html',
        })
        assert.include(messages[2], {
            n: 'pageview',
            u: 'http://localhost/pass-sanitaire-qr-code-voyages.html',
        })
    })
})
Example #15
Source File: openhours.js    From git-brunching with GNU General Public License v3.0 5 votes vote down vote up
// Testing restaurant/openhours end point
describe('GET restaurant/openhours', () => {
it('1. should return expected error if no parameters are entered', function(done) {
    chai
      .request(`${config.listen.address}:${config.listen.port}/restaurant`)
      .get('/openhours')
      .query({})
      .end((err, res) => {
        assert.isNull(err, 'Expected error to be null. Ensure an instance of the api is running');
        const { body } = res;
        assert.isObject(body, 'Expected response to contain a body object');
        assert.deepEqual(body, {error: '/restaurant/openhours GET endpoint needs a restaurantID query param'});
        done();
      });
  });

  it('2. should return expected error if incorrect parameters are entered', function(done) {
    chai
      .request(`${config.listen.address}:${config.listen.port}/restaurant`)
      .get('/openhours')
      .query({notRestaurantID:2})
      .end((err, res) => {
        assert.isNull(err, 'Expected error to be null. Ensure an instance of the api is running');
        const { body } = res;
        assert.isObject(body, 'Expected response to contain a body object');
        assert.deepEqual(body, {error: '/restaurant/openhours GET endpoint needs a restaurantID query param'});
        done();
      });
  });

  it('3. should return expected correct query when restaurantID is provided', function(done) {
    chai
      .request(`${config.listen.address}:${config.listen.port}/restaurant`)
      .get('/openhours')
      .query({restaurantID:2})
      .end((err, res) => {
        assert.isNull(err, 'Expected error to be null. Ensure an instance of the api is running');
        
        const { body } = res;
        assert.isObject(body, 'Expected response to contain a body object');
        assert.deepEqual(body, {
          "query":"SELECT DayOfWeek, OpenTime, CloseTime from HOURS WHERE RestaurantID = ?;",
          "args":["2"]
        });
        done();
      });
  });

});
Example #16
Source File: app.forms.steps.js    From webdriverio-appium-cucumber-boilerplate with Apache License 2.0 5 votes vote down vote up
Then(/^é exibido o texto '(.+)'$/, (text) => {
    assert.equal(FormScreen.getDropDownText(), text);
});
Example #17
Source File: revealjs-client-engine.spec.js    From talk-control with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: test-json.js    From ipfs-action with MIT License 5 votes vote down vote up
function verifyRoundTrip(obj, sorting) {
  const encoded = new TextDecoder().decode(encode(obj, sorting === false ? { mapSorter: null } : undefined));
  const json = JSON.stringify(obj);
  assert.strictEqual(encoded, json);
  const decoded = decode(toBytes(JSON.stringify(obj)));
  assert.deepStrictEqual(decoded, obj);
}
Example #19
Source File: MeasurementController.js    From mapapps-sketching-enhanced with Apache License 2.0 5 votes vote down vote up
describe(module.id, function () {
    it("Measurement Controller", function () {
        assert.ok(controller);
    });
});
Example #20
Source File: test-node-iterators.js    From cbor-x with MIT License 5 votes vote down vote up
suite('cbor-x iterators interface tests', function () {
  test('sync encode iterator', () => {
    const encodings = [...encodeIter(tests)]
    const decodings = encodings.map(x => decode(x))
    assert.deepStrictEqual(decodings, tests)
  })

  test('async encode iterator', async () => {
    async function * generate () {
      for (const test of tests) {
        await new Promise((resolve, reject) => setImmediate(resolve))
        yield test
      }
    }

    const chunks = []
    for await (const chunk of encodeIter(generate())) {
      chunks.push(chunk)
    }

    const decodings = chunks.map(x => decode(x))
    assert.deepStrictEqual(decodings, tests)
  })

  test('sync encode and decode iterator', () => {
    const encodings = [...encodeIter(tests)]
    assert.isTrue(encodings.every(v => Buffer.isBuffer(v)))
    const decodings = [...decodeIter(encodings)]
    assert.deepStrictEqual(decodings, tests)

    // also test decodings work with buffers multiple values in a buffer
    const concatEncoding = Buffer.concat([...encodings])
    const decodings2 = [...decodeIter([concatEncoding])]
    assert.deepStrictEqual(decodings2, tests)

    // also test decodings work with partial buffers that don't align to values perfectly
    const half1 = concatEncoding.slice(0, Math.floor(concatEncoding.length / 2))
    const half2 = concatEncoding.slice(Math.floor(concatEncoding.length / 2))
    const decodings3 = [...decodeIter([half1, half2])]
    assert.deepStrictEqual(decodings3, tests)
  })

  test('async encode and decode iterator', async () => {
    async function * generator () {
      for (const obj of tests) {
        await new Promise((resolve, reject) => setImmediate(resolve))
        yield obj
      }
    }
    const yields = []
    for await (const value of decodeIter(encodeIter(generator()))) {
      yields.push(value)
    }
    assert.deepStrictEqual(yields, tests)
  })
})
Example #21
Source File: test-node-iterators.js    From msgpackr with MIT License 5 votes vote down vote up
suite('msgpackr iterators interface tests', function () {
  test('sync encode iterator', () => {
    const encodings = [...encodeIter(tests)]
    const decodings = encodings.map(x => decode(x))
    assert.deepStrictEqual(decodings, tests)
  })

  test('async encode iterator', async () => {
    async function * generate () {
      for (const test of tests) {
        await new Promise((resolve, reject) => setImmediate(resolve))
        yield test
      }
    }

    const chunks = []
    for await (const chunk of encodeIter(generate())) {
      chunks.push(chunk)
    }

    const decodings = chunks.map(x => decode(x))
    assert.deepStrictEqual(decodings, tests)
  })

  test('sync encode and decode iterator', () => {
    const encodings = [...encodeIter(tests)]
    assert.isTrue(encodings.every(v => Buffer.isBuffer(v)))
    const decodings = [...decodeIter(encodings)]
    assert.deepStrictEqual(decodings, tests)

    // also test decodings work with buffers multiple values in a buffer
    const concatEncoding = Buffer.concat([...encodings])
    const decodings2 = [...decodeIter([concatEncoding])]
    assert.deepStrictEqual(decodings2, tests)

    // also test decodings work with partial buffers that don't align to values perfectly
    const half1 = concatEncoding.slice(0, Math.floor(concatEncoding.length / 2))
    const half2 = concatEncoding.slice(Math.floor(concatEncoding.length / 2))
    const decodings3 = [...decodeIter([half1, half2])]
    assert.deepStrictEqual(decodings3, tests)
  })

  test('async encode and decode iterator', async () => {
    async function * generator () {
      for (const obj of tests) {
        await new Promise((resolve, reject) => setImmediate(resolve))
        yield obj
      }
    }
    const yields = []
    for await (const value of decodeIter(encodeIter(generator()))) {
      yields.push(value)
    }
    assert.deepStrictEqual(yields, tests)
  })
})
Example #22
Source File: presto.test.js    From paypresto.js with Apache License 2.0 5 votes vote down vote up
describe('new Presto()', () => {
  it('initiates with a WIF key', () => {
    const pay = new Presto({ key: wif })
    assert.deepEqual(pay.privKey, key)
  })

  it('initiates with an existing key', () => {
    const pay = new Presto({ key })
    assert.deepEqual(pay.privKey, key)
  })

  it('initiates without any key in simple mode', () => {
    const pay = new Presto({
      outputs: [
        {to: '1DBz6V6CmvjZTvfjvWpvvwuM1X7GkRmWEq', satoshis: 50000}
      ]
    })
    assert.equal(pay.mode, 'simple')
  })

  it('throws error without any key in proxypay mode', () => {
    assert.throws(_ => {
      new Presto({ outputs: [{data: ['0xeeefef', 'foo', 'bar']}] })
    }, 'Must initiate Presto with P2PKH outputs only in `simple` mode')
  })

  it('throws error with invalid key', () => {
    assert.throws(_ => {
      new Presto({key: 'NOTAKEY'})
    }, 'Must initiate Presto with valid private key in `proxypay` mode')
  })

  it('creates payment with outputs', () => {
    const pay = new Presto({
      key,
      outputs: [
        {to: '1DBz6V6CmvjZTvfjvWpvvwuM1X7GkRmWEq', satoshis: 50000},
        {data: ['0xeeefef', 'foo', 'bar']}
      ]
    })
    assert.lengthOf(pay.forge.outputs, 2)
    assert.equal(pay.forge.outputs[0].satoshis, 50000)
    assert.isTrue(pay.forge.outputs[0].getScript().isPubKeyHashOut())
    assert.equal(pay.forge.outputs[1].satoshis, 0)
    assert.isTrue(pay.forge.outputs[1].getScript().chunks[0].opCodeNum === bsv.OpCode.OP_FALSE)
    assert.isTrue(pay.forge.outputs[1].getScript().chunks[1].opCodeNum === bsv.OpCode.OP_RETURN)
  })

  it('creates payment with inputs', () => {
    const pay = new Presto({
      key,
      inputs: [{
        txid: '5e3014372338f079f005eedc85359e4d96b8440e7dbeb8c35c4182e0c19a1a12',
        vout: 0,
        satoshis: 15399,
        script: '76a91410bdcba3041b5e5517a58f2e405293c14a7c70c188ac'
      }]
    })
    assert.lengthOf(pay.forge.inputs, 1)
    assert.equal(pay.forge.inputs[0].txid, '5e3014372338f079f005eedc85359e4d96b8440e7dbeb8c35c4182e0c19a1a12')
  })

  it('creates payment with existing forge instance', () => {
    const forge = new Forge({
      outputs: [{data: ['foo', 'bar']}]
    })
    const pay = new Presto({ key, forge })
    assert.lengthOf(pay.forge.outputs, 1)
    assert.isTrue(pay.forge.outputs[0].getScript().chunks[0].opCodeNum === bsv.OpCode.OP_FALSE)
    assert.isTrue(pay.forge.outputs[0].getScript().chunks[1].opCodeNum === bsv.OpCode.OP_RETURN)
  })
})
Example #23
Source File: fake.test.js    From test-automation-training with MIT License 5 votes vote down vote up
describe('sinon.fake 使用示例', () => {
    it('sinon.fake 直接调用返回匿名函数', () => {
        // create a fake that returns the text "foo"
        const fake = sinon.fake.returns('foo');
        fake(); 
        // foo
        expect(fake()).to.equal('foo');
    });

    it('sinon.fake 调用once原始函数一次', function () {
        const callback = sinon.fake();
        const proxy = once(callback);
    
        proxy();
    
        assert(callback.called);
    });

    it('sinon.fake 调用once原始函数两次', function () {
        const callback = sinon.fake();
        const proxy = once(callback);
    
        proxy();
        proxy();
    
        assert(callback.calledOnce);
    });

    it('sinon.fake 更改once的this指向并传参', function () {
        const callback = sinon.fake();
        const proxy = once(callback);
        const obj = {};
    
        proxy.call(obj, 1, 2, 3);
    
        assert(callback.calledOn(obj));
        assert(callback.calledWith(1, 2, 3));
    });

    it('sinon.fake 设置函数行为', function () {
        const callback = sinon.fake.returns(42);
        const proxy = once(callback);
        expect(proxy()).to.equal(42);
    });
});
Example #24
Source File: 01_testIntroJSI.js    From practica_dwec_gestor_presupuesto with GNU General Public License v3.0 5 votes vote down vote up
// Inicialización de la variable global presupuesto
describe("Inicialización de la variable global presupuesto", function() {
    it("Devuelve 0 si no se ha modificado el presupuesto (valor por defecto)", function() {
        assert.equal(mostrarPresupuesto(), "Tu presupuesto actual es de 0 €");
    });
});
Example #25
Source File: client.js    From redis-oplog with MIT License 5 votes vote down vote up
describe('Testing accounts functionality', function () {
    it('Should properly subscribe and login', function (done) {
        const roles = {
            "__global_roles__": [
                "coach"
            ],
            "PLAN": [
                "team"
            ],
            "c76nFngLhej8PcCdT" : [
                "subscribed",
                "coach-associated"
            ],
        };

        Meteor.subscribe('accounts_usersAssoc');
        const handle = Meteor.subscribe('accounts_userData', {
            limit: 1,
            sort: {
                createdAt: 1,
            },
            fields: {
                _id: 1,
                emails: 1,
                roles: 1,
                lastLogin: 1,
                something: 1,
            }
        });

        Meteor.call('accounts_createUser', {
            roles,
            something: true,
        }, function (err, {
            userId,
            email
        }) {
            Meteor.loginWithPassword(email, '12345', function (err) {
                const user = Meteor.user();
                assert.isObject(user.roles);

                const observer = Meteor.users.find({_id: userId}).observeChanges({
                    changed(userId, fields) {
                        assert.isDefined(fields.lastLogin);

                        observer.stop();
                        handle.stop();

                        Meteor.logout(function () {
                            done();
                        });
                    }
                });

                Meteor.call('accounts_updateUser', Meteor.userId(), {
                    $set: {
                        lastLogin: new Date(),
                    }
                });
            });
        })
    });
});
Example #26
Source File: balancer.test.js    From gateway-api with Apache License 2.0 4 votes vote down vote up
async function unitTests() {
  console.log('\nStarting Balancer tests');
  console.log('***************************************************');
  // call /start
  let pair = `${TOKENS[0]}-${TOKENS[1]}`;
  console.log(`Starting Balancer on pair ${pair}...`);
  const start = await request('get', '/eth/balancer/start', {
    pairs: JSON.stringify([pair]),
  });
  console.log(start);

  // call /gas-limit
  console.log('Calling Balancer gas-limit endpoint...');
  const gasLimit = await request('post', '/eth/balancer/gas-limit', {});
  console.log(gasLimit);

  // price buy
  console.log(`Checking buy price for ${pair}...`);
  const buyPrice = await request('post', '/eth/balancer/price', {
    base: TOKENS[0],
    quote: TOKENS[1],
    amount: AMOUNT_PRICE.toString(),
    side: 'buy',
  });
  console.log(`Buy price: ${buyPrice.price}`);

  // price sell
  console.log(`Checking sell price for ${pair}...`);
  const sellPrice = await request('post', '/eth/balancer/price', {
    base: TOKENS[0],
    quote: TOKENS[1],
    amount: AMOUNT_PRICE.toString(),
    side: 'sell',
  });
  console.log(`Sell price: ${sellPrice.price}`);

  // trade buy
  console.log(`Executing buy trade on ${pair} with ${AMOUNT_TRADE} amount...`);
  const buy = await request('post', '/eth/balancer/trade', {
    base: TOKENS[0],
    quote: TOKENS[1],
    amount: AMOUNT_TRADE.toString(),
    side: 'buy',
    limitPrice: buyPrice.price,
  });
  assert.hasAnyKeys(buy, ['txHash'], 'Buy trade failed.');
  console.log(`Buy hash - ${buy.txHash}`);
  let done = false;
  let tx1, tx2;
  console.log(`Polling...`);
  while (!done) {
    tx1 = await request('post', '/eth/poll', { txHash: buy.txHash });
    console.log(tx1);
    done = tx1.confirmed;
  }
  assert.equal(tx1.receipt.status, 1, 'Buy trade reverted.');

  done = false;

  // trade sell
  console.log(`Executing sell trade on ${pair} with ${AMOUNT_TRADE} amount...`);
  const sell = await request('post', '/eth/balancer/trade', {
    base: TOKENS[0],
    quote: TOKENS[1],
    amount: AMOUNT_TRADE.toString(),
    side: 'sell',
    limitPrice: sellPrice.price,
  });
  assert.hasAnyKeys(sell, ['txHash'], 'Sell trade failed.');
  console.log(`Sell hash - ${sell.txHash}`);
  console.log(`Polling...`);
  while (!done) {
    tx2 = await request('post', '/eth/poll', { txHash: sell.txHash });
    console.log(tx2);
    done = tx2.confirmed;
  }
  assert.equal(tx2.receipt.status, 1, 'Sell trade reverted.');

  // add tests for extreme values of limitPrice - buy and sell
  console.log(
    `Testing for failure with ${
      buyPrice.price / SCALE_FACTOR
    } buy limitPrice...`
  );
  assert.notExists(
    await request('post', '/eth/balancer/trade', {
      base: TOKENS[0],
      quote: TOKENS[1],
      amount: '1',
      side: 'buy',
      limitPrice: buyPrice.price / SCALE_FACTOR,
    })
  );

  // add tests for extreme values of minimumSlippage
  console.log(
    `Testing for failure with ${
      sellPrice.price * SCALE_FACTOR
    } sell limitPrice...`
  );
  assert.notExists(
    await request('post', '/eth/balancer/trade', {
      base: TOKENS[0],
      quote: TOKENS[1],
      amount: '1',
      side: 'sell',
      limitPrice: sellPrice.price * SCALE_FACTOR,
    })
  );
}
Example #27
Source File: test.pages.js    From mesconseilscovid with MIT License 4 votes vote down vote up
describe('Pages', function () {
    it('titre de la page', async function () {
        const page = this.test.page

        // On est redirigé vers l’introduction.
        await Promise.all([
            page.goto('http://localhost:8080/'),
            page.waitForNavigation({ url: '**/#introduction' }),
        ])

        assert.equal(
            await page.title(),
            'Mes Conseils Covid — Isolement, tests, vaccins, attestations, contact à risque…'
        )
    })

    it('on va vers une page thématique', async function () {
        const page = this.test.page

        let messages = recordConsoleMessages(page)
        await page.goto('http://localhost:8080/')
        await waitForPlausibleTrackingEvent(page, 'pageview:introduction')

        await page.click(
            '.thematiques a >> text="Passe sanitaire, que faut-il savoir\u00a0?"'
        )
        await waitForPlausibleTrackingEvent(
            page,
            'pageview:pass-sanitaire-qr-code-voyages.html'
        )

        assert.lengthOf(messages, 4)
        assert.include(messages[0], {
            n: 'pageview',
            u: 'http://localhost/',
        })
        assert.include(messages[1], {
            n: 'pageview',
            u: 'http://localhost/introduction',
        })
        assert.include(messages[2], {
            n: 'Navigue vers une thématique depuis l’accueil',
            p: '{"chemin":"/introduction → /pass-sanitaire-qr-code-voyages.html"}',
            u: 'http://localhost/introduction',
        })
        assert.include(messages[3], {
            n: 'pageview',
            u: 'http://localhost/pass-sanitaire-qr-code-voyages.html',
        })
    })

    it('redirige l’ancienne page de pédiatrie vers sa page thématique', async function () {
        const page = this.test.page

        await Promise.all([
            page.goto('http://localhost:8080/#pediatrie'),
            page.waitForNavigation({
                url: 'http://localhost:8080/conseils-pour-les-enfants.html',
            }),
        ])

        assert.equal(
            await page.title(),
            'Conseils pour mon\u00a0enfant — Mes Conseils Covid'
        )
    })

    it('on peut accéder aux CGU depuis l’accueil', async function () {
        const page = this.test.page

        // On est redirigé vers l’introduction.
        await Promise.all([
            page.goto('http://localhost:8080/'),
            page.waitForNavigation({ url: '**/#introduction' }),
        ])
        await page.waitForSelector('#page.ready')

        // On va vers la page de CGU.
        {
            let bouton = await page.waitForSelector('text="Conditions d’utilisation"')
            await Promise.all([
                bouton.click(),
                page.waitForNavigation({ url: '**/#conditionsutilisation' }),
            ])
        }

        // Conditions d’utilisation.
        {
            // On retrouve le bouton pour repartir vers le questionnaire.
            let button = await page.waitForSelector('#page.ready .js-profil-empty a')
            assert.equal((await button.innerText()).trim(), 'Démarrer le questionnaire')
            assert.equal(await button.getAttribute('href'), '#symptomes')
            // On retrouve le titre explicite.
            let titre = await page.waitForSelector('#page.ready h1')
            assert.equal(await titre.innerText(), 'Conditions d’utilisation')
        }
    })
})