簡體   English   中英

類型錯誤:expect(...).to.startsWith 不是函數 - chai 和 chakram

[英]TypeError: expect(...).to.startsWith is not a function - chai and chakram

我開始寫一些自動化測試(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

誰能幫我?

謝謝

你不需要柴串,你可以這樣做:

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

我在沒有任何外部依賴的情況下使用以下解決方案

expect(result.startsWith("string to match")).to.be.true;

聽起來可能很明顯……但是您是否安裝了該軟件包? (npm -i 柴串)

我剛剛遇到了與 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/');

我發現它更具可讀性和更清晰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM