TypeError:Expect(...)。to.startsWith不是函数-chai和chakram

Jus*_*a J 3 javascript api automation chai chakram

我开始写一些自动化测试(API)

现在,我尝试对此端点进行操作:

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

所以我加入了我的功能

expect(response.body.message).to.startsWith('https://images.dog.ceo/breeds/');   
Run Code Online (Sandbox Code Playgroud)

在测试开始时:

    var chakram = require('chakram');
var chai = require('chai');  
chai.use(require('chai-string'))
expect = chai.expect;    // Using Expect style
expect = chakram.expect;
Run Code Online (Sandbox Code Playgroud)

早些时候我没有任何问题,但是运行测试后,有了这个“期望开始...”,我得到了:TypeError:Expect(...)。to.startsWith不是一个函数-chai和chakram

谁能帮我?

谢谢

Alo*_* G. 20

我正在使用以下解决方案,没有任何外部依赖

expect(result.startsWith("string to match")).to.be.true;
Run Code Online (Sandbox Code Playgroud)


Kye*_*fus 6

您不需要柴串就可以做到:

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

甚至可以做正则表达式satisfy

或更妙的是,只需使用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
Run Code Online (Sandbox Code Playgroud)