gpt4 book ai didi

javascript - 模拟/ stub 构造函数

转载 作者:数据小太阳 更新时间:2023-10-29 04:31:29 26 4
gpt4 key购买 nike

我有以下代码:

class Clients
constructor : ->
@clients = []

createClient : (name)->

client = new Client name
@clients.push client

我正在用 Jasmine BDD 像这样测试它:

describe 'Test Constructor', ->

it 'should create a client with the name foo', ->

clients = new clients
clients.createClient 'Foo'
Client.should_have_been_called_with 'Foo'

it 'should add Foo to clients', ->

clients = new clients
clients.createClient 'Foo'

expect(clients.clients[0]).toEqual SomeStub

在我的第一个测试中,我想检查是否使用正确的名称调用了构造函数。在我的第二个中,我只想确认来自新客户端的任何内容都已添加到数组中。

我正在使用 Jasmine BDD,它可以创建 spy /模拟/ stub ,但似乎无法测试构造函数。所以我正在寻找一种方法来测试构造函数,如果有一种方法我不需要额外的库但我对任何东西都持开放态度,那就太好了。

最佳答案

在 Jasmine 中可以去除构造函数,只是语法有点出乎意料:

spy = spyOn(window, 'Clients');

换句话说,您不会删除 new 方法,而是在它所在的上下文中删除类名本身,在本例中为 window。然后,您可以链接 andReturn() 以返回您选择的假对象,或链接 andCallThrough() 以调用真正的构造函数。

另请参阅:Spying on a constructor using Jasmine

关于javascript - 模拟/ stub 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7548974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com