【问题标题】:TypeError: expect(...).to.startsWith is not a function - chai and chakramTypeError: expect(...).to.startsWith 不是函数 - chai 和 chakram
【发布时间】:2019-05-27 12:01:16
【问题描述】:
我开始写一些自动化测试(API)
现在我尝试对这个端点做:
https://dog.ceo/api/breeds/image/random
所以我添加到我的函数中
expect(response.body.message).to.startsWith('https://images.dog.ceo/breeds/');
在测试开始时:
var chakram = require('chakram');
var chai = require('chai');
chai.use(require('chai-string'))
expect = chai.expect; // Using Expect style
expect = chakram.expect;
早些时候我没有遇到任何问题,但是在运行测试后,我得到了这个“预期开始......”:
TypeError: expect(...).to.startsWith 不是函数 - chai 和 chakram
谁能帮帮我?
谢谢
【问题讨论】:
标签:
javascript
api
automation
chai
chakram
【解决方案1】:
你不需要 chai-string 你可以这样做:
expect(response.body.message).to.be.a('string').and.satisfy(msg => msg.startsWith('https://images.dog.ceo/breeds/'));
甚至可以在 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
【解决方案2】:
这听起来很明显...但是您是否安装了该软件包? (npm -i chai-string)
【解决方案3】:
我在没有任何外部依赖的情况下使用以下解决方案
expect(result.startsWith("string to match")).to.be.true;
【解决方案4】:
我刚刚遇到了与 Typescript 代码相同的问题(Typescript 转译器输出错误)。这可能与您的问题不完全相同,但可能对其他人有所帮助:
我终于意识到必须同时安装 chai-string 和 @types/chai-string 软件包才能使其工作。
我现在可以写如下内容:
import { expect } from 'chai';
const chai = require('chai');
chai.use(require('chai-string'));
expect(response.body.message).to.startWith('https://images.dog.ceo/breeds/');
我觉得它更易读、更干净