27

I started writing some automation tests(API)

Now I tried to do to this endpoint:

https://dog.ceo/api/breeds/image/random

so I added into my function

expect(response.body.message).to.startsWith('https://images.dog.ceo/breeds/');   

and at the beginning of the test:

    var chakram = require('chakram');
var chai = require('chai');  
chai.use(require('chai-string'))
expect = chai.expect;    // Using Expect style
expect = chakram.expect;

Earlier I did not have any problems but with this "expect starts..." after running test I got: TypeError: expect(...).to.startsWith is not a function - chai and chakram

Can anyone help me?

thanks

Justyna J
  • 303
  • 1
  • 3
  • 8

4 Answers4

44

You don't need chai-string you can just do:

expect(response.body.message).to.be.a('string').and.satisfy(msg => msg.startsWith('https://images.dog.ceo/breeds/'));

Can even do regex in that satisfy.

Or better then this, just use match:

const { escapeRegExp } = require('lodash');
expect(response.body.message).to.be.a('string').and.match(/^https:\/\/images\.dog\.ceo\/breeds\//i);
expect(response.body.message).to.be.a('string').and.match(new RegExp('^' + escapeRegExp('https://images.dog.ceo/breeds/'), 'i')); // this is preferred way so you don't have to worry about escaping, rely on lodash method to escape
Kyefus
  • 546
  • 5
  • 5
18

I am living with following solution without any external dependency

expect(result.startsWith("string to match")).to.be.true;
Alok G.
  • 1,388
  • 3
  • 15
  • 26
  • This works, but when the assertion fails, the error message is not very informative. – Zhiyong Jun 02 '23 at 18:17
  • @Zhiyong you can customize the message: expect(result.startsWith("string to match"), "Custom message").to.be.true; – GôTô Jun 30 '23 at 14:07
3

I just ran into the same issue with Typescript code (Typescript transpiler was outputting an error). It's probably not the exact same issue as yours, but it might help others:

I finally realized that both chai-string and @types/chai-string packages have to be installed to make it work.

I'm now able to write something like:

import { expect } from 'chai';
const chai = require('chai');  
chai.use(require('chai-string'));

expect(response.body.message).to.startWith('https://images.dog.ceo/breeds/');

which I find more readable and cleaner

Géraud
  • 1,923
  • 3
  • 20
  • 20
1

It may sounds obvious...but did you install the package? (npm -i chai-string)

arquillos
  • 87
  • 6