How to use the ok function from assert

Find comprehensive JavaScript assert.ok code examples handpicked from public code repositorys.

assert.ok is a function in Node.js that tests whether a given value is truthy, and throws an error if it is not.

2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
    const info = await algosdk.waitForConfirmation(
      this.v2Client,
      fundingResponse.txId,
      1
    );
    assert.ok(info['confirmed-round'] > 0);
  }
);

Given(
fork icon185
star icon264
watch icon27

+ 12 other calls in file

22
23
24
25
26
27
28
29
30
31
  assert.deepEqual(precinct.ast, ast);
});

it('dangles off the parsed ast from a .js file', () => {
  precinct(read('amd.js'));
  assert.ok(precinct.ast);
  assert.notDeepEqual(precinct.ast, ast);
});

it('dangles off the parsed ast from a scss detective', () => {
fork icon39
star icon177
watch icon0

How does assert.ok work?

assert.ok is a function in Node.js that tests whether a given value is truthy, and throws an error if it is not.

When called with a value, assert.ok checks whether the value is truthy using JavaScript's built-in truthiness rules, which consider values such as undefined, null, 0, and '' (empty string) to be falsy, and all other values to be truthy.

If the value is truthy, assert.ok does nothing and returns undefined. If the value is falsy, assert.ok throws an AssertionError with a default error message or a custom error message provided as a second argument.

assert.ok can be useful for validating assumptions in code and ensuring that the program is operating correctly. It is often used in automated tests to check that functions return expected values or that objects have the expected properties.

For example, suppose we have a function that calculates the sum of two numbers:

javascript
function sum(a, b) { return a + b; }

We can use assert.ok to validate that the function returns the expected value for different inputs:

javascript
const assert = require('assert'); assert.ok(sum(2, 3) === 5); // Passes assert.ok(sum(-2, 5) === 3); // Passes assert.ok(sum(2, 3) === 6, 'Expected sum to return 6'); // Throws an AssertionError with the provided message

In this example, the first two assertions pass because sum(2, 3) returns 5 and sum(-2, 5) returns 3, which are truthy values. The third assertion fails because sum(2, 3) returns 5, which is not equal to the expected value of 6, and assert.ok throws an AssertionError with the custom message provided as the third argument.

50
51
52
53
54
55
56
57
58
59
        $schema: 'https://raw.githubusercontent.com/F5Networks/f5-appsvcs-extension/master/schema/latest/as3-schema.json',
        class: 'ADC',
        schemaVersion: '3.0.0',
        id: 'declarationId'
    };
    assert.ok(validate(data), getErrorString(validate));
});

it('should validate full controls object', () => {
    const data = {
fork icon57
star icon140
watch icon51

+ 205 other calls in file

107
108
109
110
111
112
113
114
115
116
it('should match the hostname', () => {
    assert.ok(testHostname(body.Common, currentState));
});

it('should match the DNS', () => {
    assert.ok(testDns(body.Common.myDns, currentState));
});

it('should match the NTP', () => {
    assert.ok(testNtp(body.Common.myNtp, currentState));
fork icon22
star icon51
watch icon21

+ 22 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const assert = require("assert");

function isPositiveNumber(value) {
  return typeof value === "number" && value > 0;
}

// Test that the function returns true for a positive number
assert.ok(isPositiveNumber(42)); // Passes

// Test that the function returns false for a non-positive number
assert.ok(!isPositiveNumber(-10)); // Passes

// Test that the function returns false for a non-number value
assert.ok(!isPositiveNumber("42")); // Passes

// Test that the function throws an error for an undefined value
assert.throws(() => {
  isPositiveNumber(undefined);
}, /Cannot read property 'value' of undefined/); // Passes

In this example, we have a function isPositiveNumber that takes a value and returns true if the value is a positive number, and false otherwise. We use assert.ok to test the function with different inputs and validate that it returns the expected truthy or falsy values. The first three assertions use assert.ok to check that the function returns a truthy value for a positive number, and falsy values for a non-positive number and a non-number value, respectively. The fourth assertion uses assert.throws to check that the function throws an error when called with an undefined value, using a regular expression to match the error message. All of these assertions pass, indicating that the isPositiveNumber function behaves correctly according to our assumptions.

167
168
169
170
171
172
173
174
175
176
};

return new Promise((resolve, reject) => {
    const restWorker = new RestWorker();
    const success = () => {
        assert.ok(loadStateCalled);
        resolve();
    };
    const error = (err) => {
        reject(new Error(`Should have called success, but got error: ${err}`));
fork icon22
star icon51
watch icon21

+ 8 other calls in file

1692
1693
1694
1695
1696
1697
1698
1699
1700
1701

if (!noAssert) {
  assert.ok(offset !== undefined && offset !== null,
      'missing offset');

  assert.ok(offset < buffer.length,
      'Trying to read beyond buffer length');
}

if (offset >= buffer.length) return;
fork icon11
star icon21
watch icon6

+ 187 other calls in file

115
116
117
118
119
120
121
122
123
124

try {
    await quotaProxy.methods.upgradeTo(quotaDelegate._address).send({ from: accounts[0], gas: 10000000 });
    assert(false, 'Should never get here');
} catch (e) {
    assert.ok(e.message.match(/revert/));
}

try {
    await quotaProxy.methods.upgradeTo("0x0000000000000000000000000000000000000000").send({ from: accounts[0], gas: 10000000 });
fork icon10
star icon10
watch icon6

35
36
37
38
39
40
41
42
43
44
45
  mock.restore();
});


describe('Monitor class', function() {
  it('should have default instance', async () => {
    assert.ok(monitor instanceof monitor.Monitor);
  });
  it('should create new instances', async () => {
    assert.ok(tester instanceof monitor.Monitor);
  });
fork icon9
star icon93
watch icon6

+ 73 other calls in file

40
41
42
43
44
45
46
47
48
49
    let document = await vscode.workspace.openTextDocument(path.join(vscode.workspace.rootPath, 'tests', 'SampleTest.php'));
    await vscode.window.showTextDocument(document);
    await vscode.commands.executeCommand('better-phpunit.run');

    await timeout(waitToAssertInSeconds, () => {
        assert.ok(extension.getGlobalCommandInstance().method === undefined);
    });
});

it("Run file", async () => {
fork icon9
star icon37
watch icon4

32
33
34
35
36
37
38
39
40
41

describe('.browserslistrc', function() {
  it('should transpile with correct targets setting', async function() {
    const mod = porter.packet.files['utils/index.js'];
    const { code } = await mod.obtain();
    assert.ok(code.includes('async function'));
  });
});

describe('module.id', function() {
fork icon7
star icon40
watch icon9

+ 118 other calls in file

49
50
51
52
53
54
55
56
57
});

describe('packet.resolve()', function() {
  it('resolve object-inspect', async function() {
    const inspect = porter.packet.find({ name: 'object-inspect' });
    assert.ok(inspect);
    // ./util.inspect is neglected in browser field of object-inspect
    assert.ok(!inspect.files.hasOwnProperty('util.inspect.js'));
  });
fork icon7
star icon40
watch icon9

+ 34 other calls in file

81
82
83
84
85
86
87
88
89
90
});

const p = require('./napi_child').spawnSync(
  process.execPath, [__filename, 'fatal', bindingPath]);
assert.ifError(p.error);
assert.ok(p.stderr.toString().includes(
  'FATAL ERROR: Error::ThrowFatalError This is a fatal error'));

assert.throws(() => binding.error.throwDefaultError(false),
  /Cannot convert undefined or null to object/);
fork icon457
star icon0
watch icon52

235
236
237
238
239
240
241
242
243
244
assert.ifError(err);

request(nconf.get('url'), (err, res, body) => {
    assert.ifError(err);
    assert.equal(res.statusCode, 200);
    assert.ok(body);
    assert.ok(body.indexOf('<main id="panel"'));
    assert.ok(body.includes(message));

    done();
fork icon1
star icon0
watch icon5

+ 4 other calls in file

63
64
65
66
67
68
69
70
71
72

  // sign and verify
  var md = MD.sha1.create();
  md.update('0123456789abcdef');
  var signature = pair.privateKey.sign(md);
  ASSERT.ok(pair.publicKey.verify(md.digest().getBytes(), signature));
}

// compare pairs
function _pairCmp(pair1, pair2) {
fork icon0
star icon0
watch icon1

+ 5 other calls in file

38
39
40
41
42
43
44
45
46
47
  ASSERT.equal(eb64(publicKey), b64PublicKey);
});

it('should generate a random key pair', function() {
  var kp = ED25519.generateKeyPair();
  ASSERT.ok(kp.privateKey);
  ASSERT.ok(kp.publicKey);
});

it('should sign a SHA-256 digest of an UTF-8 message', function() {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

53
54
55
56
57
58
59
60
61
62
  ];
  arr[1].$timestamps(false);

  await Movie.insertMany(arr);
  const docs = await Movie.find().sort({ name: 1 });
  assert.ok(docs[0].createdAt.valueOf() >= start);
  assert.ok(!docs[1].createdAt);
});

it('insertMany() with nested timestamps (gh-12060)', async function() {
fork icon0
star icon0
watch icon494

+ 79 other calls in file

111
112
113
114
115
116
117
118
119
120

assert.ok('last_name' in doc);
assert.ok('_id' in doc);
assert.ok('first_name' in doc._id);
assert.equal(doc._id.first_name, 'Daniel');
assert.ok('age' in doc._id);
assert.equal(doc._id.age, 21);

assert.ok('doc_embed' in doc);
assert.ok('some' in doc.doc_embed);
fork icon0
star icon0
watch icon494

+ 559 other calls in file

7
8
9
10
11
12
13
14
15
16
        storage: {},
        config: {},
        urlUtils: {}
    });

    assert.ok(contentFileImporter);
    assert.equal(contentFileImporter.type, 'media');
});

it('returns configured extensions', function () {
fork icon0
star icon0
watch icon0

773
774
775
776
777
778
779
780
781
782
783
  }
}


function shouldContainInBody (str) {
  return function (res) {
    assert.ok(res.text.indexOf(str) !== -1,
      'expected \'' + res.text + '\' to contain \'' + str + '\'')
  }
}

fork icon0
star icon0
watch icon1

95
96
97
98
99
100
101
102
    assert.strictEqual(flat[0], 'one')
    assert.strictEqual(flat[1], 'two')
    assert.strictEqual(flat[2], 'three')
    assert.strictEqual(flat[3], 'four')
    assert.strictEqual(flat[4], 'five')
    assert.ok(flat.every(function (v) { return typeof v === 'string' }))
  })
})
fork icon0
star icon0
watch icon1