模拟/存根构造函数

Pic*_*els 7 javascript coffeescript jasmine

我有以下代码:

class Clients
  constructor : ->
    @clients = []

  createClient : (name)->

    client = new Client name
    @clients.push client
Run Code Online (Sandbox Code Playgroud)

我用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
Run Code Online (Sandbox Code Playgroud)

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

我正在使用Jasmine BDD,它有一种方法来创建间谍/模拟/存根,但似乎不可能测试构造函数.所以我正在研究一种测试构造函数的方法,如果有一种方法可以让我不需要额外的库,那么我会很开心.

jpa*_*kal 9

可能的存根出在茉莉花构造,语法只是有点出乎意料:

spy = spyOn(window, 'Clients');
Run Code Online (Sandbox Code Playgroud)

换句话说,你没有存根new方法,你在它所居住的上下文中存在类名本身,在这种情况下window.然后,您可以链接到a andReturn()以返回您选择的假对象,或者a andCallThrough()来调用真正的构造函数.

另请参阅:使用Jasmine监视构造函数


Kar*_*arl 4

我认为最好的计划是将新对象的创建提取Client到一个单独的方法中。Clients这将允许您单独测试类并使用模拟Client对象。

我已经编写了一些示例代码,但我还没有用 Jasmine 对其进行测试。希望您能了解其工作原理的要点:

class Clients
  constructor: (@clientFactory) ->
    @clients = []

  createClient : (name)->
    @clients.push @clientFactory.create name

clientFactory = (name) -> new Client name

describe 'Test Constructor', ->

  it 'should create a client with the name foo', ->
    mockClientFactory = (name) ->
    clients = new Clients mockClientFactory

    clients.createClient 'Foo'

    mockClientFactory.should_have_been_called_with 'Foo'

  it 'should add Foo to clients', ->
    someStub = {}
    mockClientFactory = (name) -> someStub
    clients = new Clients mockClientFactory

    clients.createClient 'Foo'

    expect(clients.clients[0]).toEqual someStub
Run Code Online (Sandbox Code Playgroud)

现在的基本计划是使用单独的函数 ( clientFactory) 来创建新Client对象。然后在测试中模拟该工厂,使您可以准确控制返回的内容,并检查它是否已被正确调用。